home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 November: Tool Chest / Dev.CD Nov 00 TC Disk 2.toast / pc / sample code / printing / scriptable print simpletext / textfile.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-28  |  83.9 KB  |  3,039 lines

  1. /*
  2. **    File:        TextFile.c
  3. **
  4. **    Contains:    Text file support for simple text application.
  5. **
  6. **    Version:    SimpleText 1.4 or later
  7. **
  8. ** Copyright 1993-1999 Apple Computer. All rights reserved.
  9. **
  10. **    You may incorporate this sample code into your applications without
  11. **    restriction, though the sample code has been provided "AS IS" and the
  12. **    responsibility for its operation is 100% yours.  However, what you are
  13. **    not permitted to do is to redistribute the source as "DSC Sample Code"
  14. **    after having made changes. If you're going to re-distribute the source,
  15. **    we require that you make it clear in the source that the code was
  16. **    descended from Apple Sample Code, but that you've made changes.
  17.  
  18. */
  19.  
  20. #include "MacIncludes.h"
  21.  
  22. #include "TextFile.h"
  23.  
  24. #pragma segment Text
  25.  
  26.  
  27.  
  28. // --------------------------------------------------------------------------------------------------------------
  29. // INTERNAL DEFINES
  30. // --------------------------------------------------------------------------------------------------------------
  31. #define kOnePageWidth         600            // preferred width of a window
  32. #define kMargins            4            // margins in window
  33. #define kPrintMargins        8            // margins in printing window
  34. #define kGXPrintMargins        10            // margins in printing a GX window
  35.  
  36. #define kPictureBase        1000        // resource base ID for PICTs in documents
  37. #define kSoundBase            10000        // resource base ID for 'snd 's in documents
  38.  
  39. // resources for controling printing
  40. #define kFormResource        'form'
  41.     #define kFormFeed            0x00000001    // form feed after this line
  42.  
  43. #define    kContentsListID        10000        // resource ID for STR# contents menu         
  44.  
  45. // some memory requirements
  46. #define kPrefBufferSize        90*1024
  47. #define kMinBufferSize        5*1024
  48.  
  49. #define kDeleteKey            8
  50. #define kForwardDeleteKey    0x75
  51.  
  52.  
  53. extern pascal void AsmClikLoop();
  54.  
  55. #define ABS(n)                (((n) < 0) ? -(n) : (n))
  56.  
  57. // --------------------------------------------------------------------------------------------------------------
  58. // GLOBALS USED ONLY BY THESE ROUTINES
  59. // --------------------------------------------------------------------------------------------------------------
  60.  
  61. // These variables are used for speech, notice that on purpose we only
  62. // support a single channel at a time.
  63. static SpeechChannel    gSpeechChannel = nil;        
  64. static VoiceSpec        gCurrentVoice;
  65. static Ptr                gSpeakPtr = nil;
  66. static Boolean            gAddedVoices = false;
  67. static Str31            gPictMarker1, gPictMarker2;
  68.  
  69. // --------------------------------------------------------------------------------------------------------------
  70. // EXTERNAL FUNCTIONS
  71. // --------------------------------------------------------------------------------------------------------------
  72.  
  73. extern OSErr    TextDragTracking(WindowRef pWindow, void *pData, DragReference theDragRef, short message);
  74. extern OSErr    TextDragReceive(WindowRef pWindow, void *refCon, DragReference theDragRef);
  75. extern Boolean    DragText(WindowRef pWindow, void *pData, EventRecord *pEvent, RgnHandle hilightRgn);
  76.  
  77. // --------------------------------------------------------------------------------------------------------------
  78. // INTERNAL ROUTINES
  79. // --------------------------------------------------------------------------------------------------------------
  80.  
  81. static void TextAddContentsMenu(WindowDataPtr pData);
  82. static void TextRemoveContentsMenu(WindowDataPtr pData);
  83. static OSErr TextGetContentsListItem(WindowDataPtr pData, short itemNum, StringPtr menuStr, StringPtr searchStr, short *totalItems);
  84. static OSErr TextAdjustContentsMenu(WindowDataPtr pData);
  85.  
  86. // --------------------------------------------------------------------------------------------------------------
  87. // UNDO UTILITY FUNCTIONS
  88. // --------------------------------------------------------------------------------------------------------------
  89. OSErr SaveCurrentUndoState(WindowDataPtr pData, short newCommandID)
  90. {
  91.     OSErr        anErr = noErr;
  92.     TEHandle    hTE = ((TextDataPtr) pData)->hTE;
  93.     
  94.     // this is only a new command if:
  95.     //    the command ID is different
  96.     // OR
  97.     //    the selection is a range, and not equal to the old one
  98.     if     (
  99.             ( ((TextDataPtr) pData)->prevCommandID != newCommandID )
  100.         ||
  101.             (
  102.                 ( (**hTE).selStart != (**hTE).selEnd )
  103.             ||
  104.                 ( ABS((**hTE).selStart - ((TextDataPtr) pData)->prevSelStart) > 1 )
  105.             )
  106.         )
  107.         {
  108.         Handle        tempHandle;
  109.         Size        tempSize;
  110.         
  111.         // if we don't have save handles, make em!
  112.         if (!((TextDataPtr) pData)->prevText)
  113.             {
  114.             ((TextDataPtr) pData)->prevText = NewHandle(0);
  115.             anErr = MemError();
  116.             nrequire(anErr, MakeTextSave);
  117.             }
  118.         if  (!((TextDataPtr) pData)->prevStyle) 
  119.             {
  120.             ((TextDataPtr) pData)->prevStyle = NewHandle(0);
  121.             anErr = MemError();
  122.             nrequire(anErr, MakeStyleSave);
  123.             }
  124.             
  125.         // grow the save handles and block move into them
  126.         tempHandle = (**hTE).hText;
  127.         tempSize = GetHandleSize(tempHandle);
  128.         SetHandleSize( ((TextDataPtr) pData)->prevText, tempSize);
  129.         anErr = MemError();
  130.         nrequire(anErr, GrowTextSave);
  131.         BlockMoveData(*tempHandle, * ((TextDataPtr) pData)->prevText, tempSize );
  132.  
  133.         tempHandle = (Handle) TEGetStyleHandle(hTE);
  134.         tempSize = GetHandleSize(tempHandle);
  135.         SetHandleSize( ((TextDataPtr) pData)->prevStyle, tempSize);
  136.         anErr = MemError();
  137.         nrequire(anErr, GrowTextSave);
  138.         BlockMoveData(*tempHandle, * ((TextDataPtr) pData)->prevStyle, tempSize );
  139.  
  140.         // save length
  141.         ((TextDataPtr) pData)->prevLength = (**hTE).teLength;
  142.         ((TextDataPtr) pData)->beforeSelStart = (**hTE).selStart;
  143.         ((TextDataPtr) pData)->beforeSelEnd = (**hTE).selEnd;
  144.         }
  145.     
  146.     // save start and end of the selection
  147.     ((TextDataPtr) pData)->prevSelStart = (**hTE).selStart;
  148.  
  149.     // if we didn't have any problems, then we can undo this operation
  150.     ((TextDataPtr) pData)->prevCommandID = newCommandID;
  151.     return(noErr);
  152.     
  153. // EXCEPTION HANDLING
  154. GrowStyleSave:
  155. GrowTextSave:
  156. MakeStyleSave:
  157. MakeTextSave:
  158.     // can't undo because of an error 
  159.     // (at some point might warn the user, but that's probably more annoying)
  160.     ((TextDataPtr) pData)->prevCommandID = cNull;
  161.     
  162.     return(anErr);
  163.     
  164. } // SaveCurrentUndoState
  165.  
  166. // --------------------------------------------------------------------------------------------------------------
  167. static void PerformUndo(WindowDataPtr pData)
  168. {
  169.     if (((TextDataPtr) pData)->prevCommandID != cNull)
  170.         {
  171.         TEHandle    hTE = ((TextDataPtr) pData)->hTE;
  172.         long        tempLong;
  173.         
  174.         // undo text
  175.         tempLong = (long) (**hTE).hText;
  176.         (**hTE).hText = ((TextDataPtr) pData)->prevText;
  177.         ((TextDataPtr) pData)->prevText = (Handle)tempLong;
  178.  
  179.         // undo length
  180.         tempLong = (long) (**hTE).teLength;
  181.         (**hTE).teLength = ((TextDataPtr) pData)->prevLength;
  182.         ((TextDataPtr) pData)->prevLength = tempLong;
  183.  
  184.         // undo style
  185.         tempLong = (long) TEGetStyleHandle(hTE);
  186.         if (HandToHand((Handle*) &tempLong) == noErr)
  187.             {
  188.             TESetStyleHandle( (TEStyleHandle) ((TextDataPtr) pData)->prevStyle, hTE );
  189.             ((TextDataPtr) pData)->prevStyle = (Handle)tempLong;
  190.             }
  191.             
  192.         // undo selection
  193.             {
  194.             short    start, end;
  195.             
  196.             start = ((TextDataPtr) pData)->beforeSelStart;
  197.             end = ((TextDataPtr) pData)->beforeSelEnd;
  198.             ((TextDataPtr) pData)->prevSelStart = (**hTE).selStart;
  199.             TESetSelect(start, end, hTE);
  200.             }
  201.         
  202.         }
  203.         
  204. } // PerformUndo
  205.  
  206.  
  207. // --------------------------------------------------------------------------------------------------------------
  208. // TEXT EDIT UTILITY FUNCTIONS
  209. // --------------------------------------------------------------------------------------------------------------
  210. static long CalculateTextEditHeight(TEHandle hTE)
  211. {
  212.     long    result;
  213.     short    length;
  214.     
  215.     result = TEGetHeight(32767, 0, hTE);
  216.     length = (**hTE).teLength;
  217.     
  218.     // Text Edit doesn't return the height of the last character, if that
  219.     // character is a <cr>.  So if we see that, we go grab the height of
  220.     // that last character and add it into the total height.
  221.     if ( (length) && ( (*(**hTE).hText)[length-1] == '\n') )
  222.         {
  223.         TextStyle    theStyle;
  224.         short        theHeight;
  225.         short        theAscent;
  226.  
  227.         TEGetStyle(length, &theStyle, &theHeight, &theAscent, hTE);
  228.         result += theHeight;
  229.         }
  230.  
  231.     return result;
  232.  
  233. } // CalculateTextEditHeight
  234.  
  235. // --------------------------------------------------------------------------------------------------------------
  236. void AdjustTE(WindowDataPtr pData, Boolean doScroll)
  237. {
  238.     TEPtr        te;
  239.     short        value;
  240.     short        prevValue;
  241.     
  242.     te = *((TextDataPtr) pData)->hTE;
  243.     prevValue = GetControlValue(pData->vScroll);
  244.     value = te->viewRect.top - te->destRect.top;
  245.     SetControlValue(pData->vScroll, value);
  246.  
  247.     te = *((TextDataPtr) pData)->hTE;
  248.     if (doScroll)
  249.         {
  250.         short    hScroll = te->viewRect.left - te->destRect.left;
  251.         short    vScroll = value - prevValue;
  252.         if ((hScroll != 0) || (vScroll != 0))
  253.             TEScroll(hScroll, vScroll, ((TextDataPtr) pData)->hTE);
  254.         }
  255.     
  256.             
  257. } // AdjustTE
  258.  
  259. // --------------------------------------------------------------------------------------------------------------
  260.  
  261. static void RecalcTE(WindowDataPtr pData, Boolean doInval)
  262. {
  263.     Rect    viewRect, destRect;
  264.     short    oldOffset;
  265.     
  266.     destRect = (**((TextDataPtr) pData)->hTE).destRect;
  267.     viewRect = (**((TextDataPtr) pData)->hTE).viewRect;
  268.     oldOffset = destRect.top - viewRect.top;
  269.     
  270.     viewRect = pData->contentRect;
  271.             
  272.     InsetRect(&viewRect, kMargins, kMargins);
  273.     destRect = viewRect;
  274.     
  275.     OffsetRect(&destRect, 0, oldOffset);
  276.     
  277.     (**((TextDataPtr) pData)->hTE).viewRect = viewRect;
  278.     (**((TextDataPtr) pData)->hTE).destRect = destRect;
  279.     
  280.     TECalText(((TextDataPtr) pData)->hTE);
  281.  
  282.     if (doInval)
  283.         InvalRect(&qd.thePort->portRect);
  284.     
  285. } // RecalcTE
  286.  
  287. // --------------------------------------------------------------------------------------------------------------
  288.  
  289. pascal TEClickLoopUPP GetOldClickLoop(void)
  290. {
  291.     return ((TextDataPtr) FrontWindow())->docClick;
  292.     
  293. } // GetOldClikLoop
  294.  
  295. pascal void TextClickLoop(void)
  296. {    
  297.     WindowRef    window;
  298.     RgnHandle    region;
  299.     
  300.     window = FrontWindow();
  301.     region = NewRgn();
  302.     GetClip(region);                    /* save clip */
  303.     ClipRect(&GetWindowPort(window)->portRect);
  304.     ((TextDataPtr) window)->insideClickLoop = true;
  305.         AdjustScrollBars(window, false, false, nil);
  306.     ((TextDataPtr) window)->insideClickLoop = false;
  307.     SetClip(region);                    /* restore clip */
  308.     DisposeRgn(region);
  309.  
  310. } // TextClickLoop
  311.  
  312. #if GENERATINGPOWERPC
  313. static pascal Boolean CClikLoop(TEPtr pTE)
  314. {
  315.     CallTEClickLoopProc(GetOldClickLoop(), pTE);
  316.     
  317.     TextClickLoop();
  318.     
  319.     return(true);
  320.     
  321. } // CClikLoop
  322.  
  323.     static RoutineDescriptor gMyClickLoopRD = BUILD_ROUTINE_DESCRIPTOR(uppTEClickLoopProcInfo, CClikLoop);
  324.     static TEClickLoopUPP gMyClickLoop = &gMyClickLoopRD;
  325. #else
  326.     static TEClickLoopUPP gMyClickLoop = NewDrawHookProc(AsmClikLoop);
  327. #endif
  328.  
  329. // --------------------------------------------------------------------------------------------------------------
  330. #if GENERATINGPOWERPC
  331. pascal void MyDrawHook ( unsigned short offset, unsigned short textLen,
  332.      Ptr textPtr, TEPtr tePtr, TEHandle teHdl )
  333. #else
  334. pascal void MyDrawGlue();
  335.  
  336. pascal void MyDrawHook ( TEHandle teHdl, TEPtr tePtr, Ptr textPtr, short textLen, short offset )
  337. #endif
  338. {
  339. #pragma unused    ( teHdl, tePtr)
  340.  
  341.     register short            drawLen = 0;
  342.     register Ptr            drawPtr;
  343.     
  344.     drawPtr = textPtr + (long)offset;
  345.     
  346.     while ( textLen--)
  347.         {
  348.         if ( *drawPtr == 0xCA &&
  349.              ( *(drawPtr - 1) == 0x0D || *tePtr->hText == textPtr) )
  350.             {
  351.             DrawText( textPtr, offset, drawLen);
  352.             DrawChar( '\040');
  353.             offset += drawLen + 1;
  354.             drawLen = 0;
  355.             }
  356.         else
  357.             {
  358.             ++drawLen;
  359.             }
  360.         ++drawPtr;
  361.         }
  362.     
  363.     DrawText( textPtr, offset, drawLen);
  364.     
  365. } // MyDrawHook
  366.  
  367. #if GENERATINGCFM
  368.     static RoutineDescriptor gMyDrawGlueRD = BUILD_ROUTINE_DESCRIPTOR(uppDrawHookProcInfo, MyDrawHook);
  369.     static DrawHookUPP gMyDrawGlue = &gMyDrawGlueRD;
  370. #else
  371.     static DrawHookUPP gMyDrawGlue = NewDrawHookProc(MyDrawGlue);
  372. #endif
  373.  
  374. // --------------------------------------------------------------------------------------------------------------
  375. static void DisposeOfSpeech(Boolean throwAway)
  376. {
  377.     if (gSpeechChannel)
  378.         {
  379.         (void) StopSpeech( gSpeechChannel );
  380.         if (throwAway)
  381.             {
  382.             (void) DisposeSpeechChannel( gSpeechChannel );
  383.             gSpeechChannel = nil;
  384.             }
  385.         }
  386.     if (gSpeakPtr)
  387.         {
  388.         DisposePtr(gSpeakPtr);
  389.         gSpeakPtr = nil;
  390.         }
  391.         
  392. } // DisposeOfSpeech
  393.  
  394. // --------------------------------------------------------------------------------------------------------------
  395.  
  396. static Boolean FindNextPicture(Handle textHandle, short *offset, short *delta)
  397. {
  398.     long result;
  399.     
  400.     // marker at begining of document means a picture there
  401.     if ( (*offset == 0) && ( (*(unsigned char*)(*textHandle + (*offset))) == 0xCA) )
  402.         {
  403.         *delta = 1;
  404.         return true;
  405.         }
  406.  
  407.     if (gPictMarker1[0] != 0)
  408.         {
  409.         result = Munger(textHandle, *offset, &gPictMarker1[1], gPictMarker1[0], nil, 0);
  410.         if (result >= 0)
  411.             {
  412.             *offset = result;
  413.             *delta = gPictMarker1[0];
  414.             return true;
  415.             }
  416.         }
  417.  
  418.     if (gPictMarker2[0] != 0)
  419.         {
  420.         result = Munger(textHandle, *offset, &gPictMarker2[1], gPictMarker2[0], nil, 0);
  421.         if (result >= 0)
  422.             {
  423.             *offset = result;
  424.             *delta = gPictMarker2[0];
  425.             return true;
  426.             }
  427.         }
  428.         
  429.     *delta = 1;
  430.     return false;
  431.     
  432. } // FindNextPicture
  433.  
  434. // --------------------------------------------------------------------------------------------------------------
  435. static Boolean LineHasPageBreak(short lineNum, TEHandle hTE)
  436. {
  437.     Boolean        result = false;
  438.     short        offset, delta, lineStartOffset;
  439.     short        textLength;
  440.     Handle        textHandle;
  441.     short        pictIndex = 0;
  442.     
  443.     textHandle = (** hTE).hText;
  444.     lineStartOffset = (**hTE).lineStarts[lineNum];
  445.     textLength = (**hTE).lineStarts[lineNum+1];
  446.     
  447.     offset = 0;
  448.     while (offset < textLength)
  449.         {
  450.         if (FindNextPicture(textHandle, &offset, &delta))
  451.             {
  452.             Handle    formHandle;
  453.             
  454.             formHandle = Get1Resource(kFormResource, kFormResource + pictIndex);
  455.             if (formHandle)
  456.                 {
  457.                 long    options = **(long**)formHandle;
  458.                 
  459.                 ReleaseResource(formHandle);
  460.                 if ( (options & kFormFeed) && (offset >= lineStartOffset) && (offset < textLength) )
  461.                     {
  462.                     result = true;
  463.                     break;
  464.                     }
  465.                 }
  466.             ++pictIndex;
  467.             }
  468.         
  469.         offset += delta;
  470.         }
  471.         
  472.     return(result);
  473.     
  474. } // LineHasPageBreak
  475.  
  476. // --------------------------------------------------------------------------------------------------------------
  477. #define USE_PICT_SPOOL_CACHE 1
  478.  
  479. enum {kSpoolCacheBlockSize = 1024};        // 1K is arbitrary, perhaps could be tuned
  480.  
  481. static Handle    gSpoolPicture;
  482. static long        gSpoolOffset;
  483. static Handle    gSpoolCacheBlock;
  484. static long        gSpoolCacheOffset;
  485. static long        gSpoolCacheSize;
  486.  
  487. // --------------------------------------------------------------------------------------------------------------
  488. /*
  489.     ReadPartialResource is very painful over slow links such as ARA or ISDN. This code implements a simple
  490.     cache that vastly improves the performance of displaying embedded pictures over a slow network link.
  491.     The cache also improves scrolling performance in documents with many embedded pictures, even on local
  492.     volumes.
  493. */
  494. static short ReadPartialData(Ptr dataPtr, short byteCount)
  495. {
  496. #if USE_PICT_SPOOL_CACHE
  497.  
  498.     if (gSpoolCacheBlock == NULL)
  499.         {
  500.         gSpoolCacheBlock = NewHandle(kSpoolCacheBlockSize);
  501.         if (gSpoolCacheBlock != NULL)
  502.             {
  503.             long    cacheBytes    = GetResourceSizeOnDisk(gSpoolPicture) - gSpoolOffset;
  504.             
  505.             if (cacheBytes > kSpoolCacheBlockSize)
  506.                 cacheBytes = kSpoolCacheBlockSize;
  507.             
  508.             HLock(gSpoolCacheBlock);
  509.             ReadPartialResource(gSpoolPicture, gSpoolOffset, *gSpoolCacheBlock, cacheBytes);
  510.             HUnlock(gSpoolCacheBlock);
  511.             
  512.             gSpoolCacheOffset = gSpoolOffset;
  513.             gSpoolCacheSize = cacheBytes;
  514.             }
  515.         }
  516.     
  517.     // if the requested data is entirely present in the cache block, get it from there…
  518.     if (gSpoolCacheBlock != NULL &&
  519.         gSpoolOffset >= gSpoolCacheOffset && gSpoolOffset + byteCount <= gSpoolCacheOffset + gSpoolCacheSize)
  520.         {
  521.         BlockMoveData(*gSpoolCacheBlock + (gSpoolOffset - gSpoolCacheOffset), dataPtr, byteCount);
  522.         return byteCount;
  523.         }
  524.     // …else read it directly from disk, and force the cache block to be filled with new data
  525.     else
  526.         {
  527.         ReadPartialResource(gSpoolPicture, gSpoolOffset, dataPtr, byteCount);
  528.         if (gSpoolCacheBlock != NULL)
  529.             {
  530.             DisposeHandle(gSpoolCacheBlock);
  531.             gSpoolCacheBlock = NULL;
  532.             }
  533.         return byteCount;
  534.         }
  535.  
  536. #else
  537.  
  538.     ReadPartialResource(gSpoolPicture, gSpoolOffset, dataPtr, byteCount);
  539.     return byteCount;
  540.     
  541. #endif
  542.     
  543. } // ReadPartialData
  544.  
  545. // --------------------------------------------------------------------------------------------------------------
  546. static pascal void GetPartialPICTData(Ptr dataPtr,short byteCount)
  547. {
  548.     while (byteCount > 0)
  549.     {
  550.         short    readBytes    = ReadPartialData(dataPtr, byteCount);
  551.         
  552.         byteCount -= readBytes;
  553.         dataPtr += readBytes;
  554.         
  555.         gSpoolOffset += readBytes;
  556.     }
  557.     
  558. } // GetPartialPICTData
  559.  
  560. #if GENERATINGCFM
  561.     static RoutineDescriptor gGetPartialPICTDataRD = BUILD_ROUTINE_DESCRIPTOR(uppQDGetPicProcInfo, GetPartialPICTData);
  562.     static QDGetPicUPP gGetPartialPICTData = &gGetPartialPICTDataRD;
  563. #else
  564.     static QDGetPicUPP gGetPartialPICTData = NewQDGetPicProc(GetPartialPICTData);
  565. #endif
  566.  
  567. // --------------------------------------------------------------------------------------------------------------
  568. static void SpoolDrawPicture(Handle spoolPicture, PicHandle pictureHeader, Rect *pRect)
  569. {
  570.     CQDProcs    spoolProcs;
  571.     QDProcs        *oldProcs;
  572.  
  573.     gSpoolPicture = spoolPicture;
  574.     gSpoolOffset = sizeof(Picture);
  575.     
  576.     if (gMachineInfo.theEnvirons.hasColorQD)
  577.         SetStdCProcs(&spoolProcs);
  578.     else
  579.         SetStdProcs((QDProcs*) &spoolProcs);
  580.         
  581.     spoolProcs.getPicProc = gGetPartialPICTData;
  582.     oldProcs = qd.thePort->grafProcs;
  583.     qd.thePort->grafProcs = (QDProcs*) &spoolProcs;
  584.         DrawPicture(pictureHeader, pRect);
  585.     qd.thePort->grafProcs = oldProcs;
  586.     
  587.     if (gSpoolCacheBlock != NULL)
  588.         {
  589.         DisposeHandle(gSpoolCacheBlock);
  590.         gSpoolCacheBlock = NULL;
  591.         }
  592.     
  593. } // SpoolDrawPicture
  594.  
  595. // --------------------------------------------------------------------------------------------------------------
  596. static void DrawPictures( WindowDataPtr pData, TEHandle hTE)
  597. {
  598.     Handle    textHandle;
  599.     long    textLength;
  600.     short    oldResFile;
  601.     short    pictIndex;
  602.     short    numPicts;
  603.     
  604.     oldResFile = CurResFile();
  605.     UseResFile(pData->resRefNum);
  606.     
  607.     numPicts = Count1Resources('PICT');
  608.     pictIndex = 0;
  609.     
  610.     if (numPicts != 0)
  611.         {
  612.         short                offset, delta;
  613.         RgnHandle            oldClip;
  614.         Rect                theRect;
  615.         Rect                viewRect;
  616.         
  617.         viewRect = theRect = (** hTE).viewRect;
  618.         // intersect our viewing area with the actual clip to avoid
  619.         // drawing over the scroll bars
  620.             {
  621.             RgnHandle    newClip = NewRgn();
  622.             
  623.             oldClip = NewRgn();
  624.             GetClip(oldClip);
  625.             RectRgn(newClip, &theRect);
  626.             SectRgn(oldClip, newClip, newClip);
  627.             SetClip(newClip);
  628.             }
  629.         textHandle = (** hTE).hText;
  630.         textLength = (** hTE).teLength;
  631.         
  632.         offset = 0;
  633.         while (offset < textLength)
  634.             {
  635.             if (FindNextPicture(textHandle, &offset, &delta))
  636.                 {
  637.                 Handle        pictHandle;
  638.                 Point        picturePoint = TEGetPoint(offset, hTE);
  639.                 
  640.                 SetResLoad(false);
  641.                 pictHandle = Get1Resource('PICT', kPictureBase + pictIndex);
  642.                 SetResLoad(true);
  643.                 if (pictHandle)
  644.                     {
  645.                     PicHandle    pictHeader = (PicHandle)NewHandle(sizeof(Picture) + sizeof(long)*8);
  646.                     
  647.                     if (pictHeader)
  648.                         {
  649.                         HLock((Handle) pictHeader);
  650.                         ReadPartialResource(pictHandle, 0, (Ptr)*pictHeader, GetHandleSize((Handle)pictHeader));
  651.                         HUnlock((Handle) pictHeader);
  652.                         
  653.                         // calculate where to draw the picture, this location is
  654.                         // computed by:
  655.                         //  1) the frame of the original picture, normalized to 0,0
  656.                         //    2) the location of the non-breaking space character
  657.                         //    3) centering the picture on the content frame horizontally
  658.                         //    4) subtracting off the line-height of the character
  659.                         
  660.                         GetPICTRectangleAt72dpi(pictHeader, &theRect);
  661.                         OffsetRect(&theRect, -theRect.left, -theRect.top);
  662.                         OffsetRect(&theRect, 
  663.                                             theRect.left +
  664.                                             ((viewRect.right - viewRect.left) >> 1) -
  665.                                             ((theRect.right - theRect.left) >> 1),
  666.                                         picturePoint.v-theRect.top - pData->vScrollAmount);
  667.     
  668.                         // only draw the picture if it will be visible (vastly improves scrolling
  669.                         // performance in documents with many embedded pictures)
  670.                         
  671.                         if (RectInRgn(&theRect, qd.thePort->clipRgn))
  672.                             SpoolDrawPicture(pictHandle, pictHeader, &theRect);
  673.                         }
  674.                     ReleaseResource((Handle) pictHandle);
  675.                     }
  676.                 ++pictIndex;
  677.  
  678.                 offset += delta;
  679.                 }
  680.             else
  681.                 break;
  682.             }
  683.                 
  684.         SetClip(oldClip);
  685.         DisposeRgn(oldClip);
  686.         }
  687.         
  688.     UseResFile(oldResFile);
  689.     
  690. } // DrawPictures
  691.  
  692. // --------------------------------------------------------------------------------------------------------------
  693. static void UpdateFileInfo(FSSpec *pSpec, Boolean documentIsText)
  694. {
  695.     FInfo    theInfo;
  696.  
  697.     FSpGetFInfo(pSpec, &theInfo);
  698.     theInfo.fdCreator = 'ttxt';
  699.  
  700.     // set the stationary bit, if we must
  701.     if (!documentIsText)
  702.         {
  703.         theInfo.fdFlags |= kIsStationery;
  704.         theInfo.fdType = 'sEXT';
  705.         }
  706.     else
  707.         {
  708.         theInfo.fdFlags &= ~kIsStationery;
  709.         theInfo.fdType = 'TEXT';
  710.         }
  711.     FSpSetFInfo(pSpec, &theInfo);
  712.  
  713. } // UpdateFileInfo
  714.  
  715. // --------------------------------------------------------------------------------------------------------------
  716. static OSErr    TextSave(WindowDataPtr pData)
  717. {
  718.     OSErr    anErr = noErr;
  719.     long    amountToWrite;
  720.     
  721.     // write out the text
  722.     SetFPos(pData->dataRefNum, fsFromStart, 0);
  723.     amountToWrite = (** ((TextDataPtr) pData)->hTE).teLength;
  724.     anErr = FSWrite(pData->dataRefNum, &amountToWrite, * (** ((TextDataPtr) pData)->hTE).hText);
  725.     nrequire(anErr, FailedWrite);
  726.     SetEOF(pData->dataRefNum, amountToWrite);
  727.     
  728.     if (pData->resRefNum == -1)
  729.         {
  730.         FSpCreateResFile(&pData->fileSpec, 'ttxt', pData->originalFileType, 0);
  731.         pData->resRefNum = FSpOpenResFile(&pData->fileSpec, fsRdWrPerm);            
  732.         }
  733.     else
  734.         {
  735.         // a save always makes it into file of type 'TEXT', for Save As… we 
  736.         // afterwards set it again if the user is saving as stationary.
  737.         UpdateFileInfo(&pData->fileSpec, true);
  738.         }
  739.  
  740.     if (pData->resRefNum != -1)
  741.         {
  742.         short    oldResFile = CurResFile();
  743.         Handle    resourceHandle;
  744.         
  745.         UseResFile(pData->resRefNum);
  746.         
  747.         // remove any old sounds
  748.         resourceHandle = Get1Resource('snd ', kSoundBase);
  749.         if (resourceHandle)
  750.             {
  751.             RemoveResource(resourceHandle);
  752.             DisposeHandle(resourceHandle);
  753.             }
  754.             
  755.         // save the new sound
  756.         resourceHandle = ((TextDataPtr) pData)->soundHandle;
  757.         if (resourceHandle)
  758.             {
  759.             anErr = HandToHand(&resourceHandle);
  760.             if (anErr == noErr)
  761.                 {
  762.                 AddResource(resourceHandle, 'snd ', kSoundBase, "\p");
  763.                 anErr = ResError();
  764.                 }
  765.             nrequire(anErr, AddSoundResourceFailed);
  766.             }
  767.             
  768.         // remove any old styles
  769.         resourceHandle = Get1Resource('styl', 128);
  770.         if (resourceHandle)
  771.             {
  772.             RemoveResource(resourceHandle);
  773.             DisposeHandle(resourceHandle);
  774.             }
  775.         
  776.         // save the new style -- get the scrap handle from the TE record
  777.         // To do this, we must select the text -- BUT doing so through the
  778.         // TextEdit API results in lots of flashing and annoying behavior.
  779.         // So we just change the offsets by hand
  780.         {
  781.         short                oldStart, oldEnd;    
  782.         
  783.         oldStart = (** ((TextDataPtr) pData)->hTE).selStart;
  784.         oldEnd   = (** ((TextDataPtr) pData)->hTE).selEnd;
  785.         
  786.         (** ((TextDataPtr) pData)->hTE).selStart = 0;
  787.         (** ((TextDataPtr) pData)->hTE).selEnd = 32767;
  788.     
  789.         resourceHandle = (Handle) TEGetStyleScrapHandle( ((TextDataPtr) pData)->hTE );
  790.     
  791.         (** ((TextDataPtr) pData)->hTE).selStart = oldStart;
  792.         (** ((TextDataPtr) pData)->hTE).selEnd = oldEnd;
  793.         }
  794.     
  795.         if (resourceHandle)
  796.             {
  797.             AddResource(resourceHandle, 'styl', 128, "\p");
  798.             anErr = ResError();
  799.             nrequire(anErr, AddStyleResourceFailed);
  800.             }
  801.             
  802.         AddSoundResourceFailed:
  803.         AddStyleResourceFailed:    
  804.         
  805.             UpdateResFile(pData->resRefNum);
  806.             UseResFile(oldResFile);
  807.         }
  808.  
  809.         
  810. // FALL THROUGH EXCEPTION HANDLING
  811. FailedWrite:
  812.  
  813.     // if everything went okay, then clear the changed bit
  814.     if (anErr == noErr)
  815.         {
  816.         pData->changed = false;
  817.         (void) FlushVol("\p", pData->fileSpec.vRefNum);
  818.         }
  819.         
  820.     return anErr;
  821.     
  822. } // TextSave
  823.  
  824. // --------------------------------------------------------------------------------------------------------------
  825.  
  826. static pascal void DrawTextUserItem(DialogPtr dPtr, short theItem)
  827. /*
  828.     Draw text icon in the location
  829. */
  830. {
  831.     short        kind;
  832.     Handle        itemHandle;
  833.     Rect        box;
  834.     
  835.     GetDialogItem(dPtr, theItem, &kind, &itemHandle, &box);
  836.     PlotIconID(&box, ttNone, ttNone, kTextIcon);
  837.             
  838. } // DrawTextUserItem
  839.  
  840. #if GENERATINGCFM
  841.     static RoutineDescriptor gDrawTextUserItemRD = BUILD_ROUTINE_DESCRIPTOR(uppUserItemProcInfo, DrawTextUserItem);
  842.     static UserItemUPP gDrawTextUserItem = &gDrawTextUserItemRD;
  843. #else
  844.     static UserItemUPP gDrawTextUserItem = NewUserItemProc(DrawTextUserItem);
  845. #endif
  846.  
  847. // --------------------------------------------------------------------------------------------------------------
  848.  
  849. static pascal void DrawStationeryUserItem(DialogPtr dPtr, short theItem)
  850. /*
  851.     Draw stationery icon in the location
  852. */
  853. {
  854.     short        kind;
  855.     Handle        itemHandle;
  856.     Rect        box;
  857.     
  858.     GetDialogItem(dPtr, theItem, &kind, &itemHandle, &box);
  859.     PlotIconID(&box, ttNone, ttNone, kStationeryIcon);
  860.             
  861. } // DrawStationeryUserItem
  862.  
  863.  
  864. #if GENERATINGCFM
  865.     static RoutineDescriptor gDrawStationeryUserItemRD = BUILD_ROUTINE_DESCRIPTOR(uppUserItemProcInfo, DrawStationeryUserItem);
  866.     static UserItemUPP gDrawStationeryUserItem = &gDrawStationeryUserItemRD;
  867. #else
  868.     static UserItemUPP gDrawStationeryUserItem = NewUserItemProc(DrawStationeryUserItem);
  869. #endif
  870.  
  871.  
  872. // --------------------------------------------------------------------------------------------------------------
  873. // pre and post update procs for inline input 
  874.  
  875. static pascal void TSMPreUpdateProc(TEHandle textH, long refCon)
  876. {
  877. #pragma unused (refCon)
  878.  
  879.     ScriptCode     keyboardScript;
  880.     short        mode;
  881.     TextStyle    theStyle;
  882.  
  883.     keyboardScript = GetScriptManagerVariable(smKeyScript);
  884.     mode = doFont;
  885.     if     (!
  886.             (
  887.             (TEContinuousStyle(&mode, &theStyle, textH) )&& 
  888.             (FontToScript(theStyle.tsFont) == keyboardScript) 
  889.             )
  890.         )
  891.         {
  892.         theStyle.tsFont = GetScriptVariable(keyboardScript, smScriptAppFond);
  893.         TESetStyle(doFont, &theStyle, false, textH);
  894.         }
  895.         
  896. } // TSMPreUpdateProc
  897.  
  898. #if GENERATINGCFM
  899.     static RoutineDescriptor gTSMPreUpdateProcRD = BUILD_ROUTINE_DESCRIPTOR(uppTSMTEPreUpdateProcInfo, TSMPreUpdateProc);
  900.     static TSMTEPreUpdateUPP gTSMPreUpdateProc = &gTSMPreUpdateProcRD;
  901. #else
  902.     static TSMTEPreUpdateUPP gTSMPreUpdateProc = NewTSMTEPreUpdateProc(TSMPreUpdateProc);
  903. #endif
  904.  
  905. static pascal void TSMPostUpdateProc(
  906.                 TEHandle textH,
  907.                 long fixLen,
  908.                 long inputAreaStart,
  909.                 long inputAreaEnd,
  910.                 long pinStart,
  911.                 long pinEnd,
  912.                 long refCon)
  913. {
  914. #pragma unused (textH, fixLen, inputAreaStart, inputAreaEnd, pinStart, pinEnd)
  915.  
  916.     AdjustScrollBars((WindowRef)refCon, false, false, nil);
  917.     AdjustTE((WindowDataPtr)refCon, true);
  918.     
  919.     ((WindowDataPtr)refCon)->changed = true;
  920.     
  921. } // TSMPostUpdateProc
  922.  
  923. #if GENERATINGCFM
  924.     static RoutineDescriptor gTSMPostUpdateProcRD = BUILD_ROUTINE_DESCRIPTOR(uppTSMTEPostUpdateProcInfo, TSMPostUpdateProc);
  925.     static TSMTEPostUpdateUPP gTSMPostUpdateProc = &gTSMPostUpdateProcRD;
  926. #else
  927.     static TSMTEPostUpdateUPP gTSMPostUpdateProc = NewTSMTEPostUpdateProc(TSMPostUpdateProc);
  928. #endif
  929.  
  930. // --------------------------------------------------------------------------------------------------------------
  931.  
  932. static pascal short SaveDialogHook(short item, DialogPtr dPtr, Boolean *isText)
  933. {
  934.     short    theType;
  935.     Handle    theHandle;
  936.     Rect    theRect;
  937.     short    returnValue = item;
  938.     
  939.  
  940.     switch (item)
  941.         {
  942.         case sfHookFirstCall:
  943.             if (GetWRefCon(GetDialogWindow(dPtr)) == sfMainDialogRefCon)
  944.                 {
  945.                 GetDialogItem(dPtr, iTextUserItem, &theType, &theHandle, &theRect);
  946.                 theHandle = (Handle) gDrawTextUserItem;
  947.                 SetDialogItem(dPtr, iTextUserItem, theType, theHandle, &theRect);
  948.                 
  949.                 GetDialogItem(dPtr, iStationeryUserItem, &theType, &theHandle, &theRect);
  950.                 theHandle = (Handle) gDrawStationeryUserItem;
  951.                 SetDialogItem(dPtr, iStationeryUserItem, theType, theHandle, &theRect);
  952.     
  953.                 GetDialogItem(dPtr, iTextDocumentItem, &theType, &theHandle, &theRect);
  954.                 SetControlValue((ControlHandle) theHandle, 1);
  955.                 
  956.                 GetDialogItem(dPtr, iStationeryDocumentItem, &theType, &theHandle, &theRect);
  957.                 SetControlValue((ControlHandle) theHandle, 0);
  958.                 *isText = true;
  959.                 }
  960.             break;
  961.             
  962.         case iTextDocumentItem:
  963.         case iTextUserItem:
  964.             GetDialogItem(dPtr, iTextDocumentItem, &theType, &theHandle, &theRect);
  965.             SetControlValue((ControlHandle) theHandle, 1);
  966.             
  967.             GetDialogItem(dPtr, iStationeryDocumentItem, &theType, &theHandle, &theRect);
  968.             SetControlValue((ControlHandle) theHandle, 0);
  969.             
  970.             *isText = true;
  971.             returnValue = sfHookNullEvent;
  972.             break;
  973.             
  974.         case iStationeryDocumentItem:
  975.         case iStationeryUserItem:
  976.             GetDialogItem(dPtr, iTextDocumentItem, &theType, &theHandle, &theRect);
  977.             SetControlValue((ControlHandle) theHandle, 0);
  978.             
  979.             GetDialogItem(dPtr, iStationeryDocumentItem, &theType, &theHandle, &theRect);
  980.             SetControlValue((ControlHandle) theHandle, 1);
  981.             
  982.             *isText = false;
  983.             returnValue = sfHookNullEvent;
  984.             break;
  985.         
  986.         }
  987.         
  988.     return returnValue;
  989.     
  990. } // SaveDialogHook
  991.  
  992. #if GENERATINGCFM
  993.     static RoutineDescriptor gSaveDialogHookRD = BUILD_ROUTINE_DESCRIPTOR(uppDlgHookYDProcInfo, SaveDialogHook);
  994.     static DlgHookYDUPP gSaveDialogHook = &gSaveDialogHookRD;
  995. #else
  996.     static DlgHookYDUPP gSaveDialogHook = NewDlgHookYDProc(SaveDialogHook);
  997. #endif
  998.  
  999. // --------------------------------------------------------------------------------------------------------------
  1000.  
  1001. // Handle update/activate events behind Standard File
  1002. static pascal Boolean SaveDialogFilter(DialogPtr theDialog, EventRecord *theEvent,
  1003.                                       short *itemHit, void *myDataPtr)
  1004. {
  1005.     #pragma unused(myDataPtr)
  1006.  
  1007.     if (StdFilterProc(theDialog, theEvent, itemHit))
  1008.         return true;
  1009.  
  1010.     // Pass updates through (Activates are tricky...was mucking with Apple menu & thereby
  1011.     // drastically changing how the system handles the menu bar during our alert)
  1012.     if (theEvent->what == updateEvt /* || theEvent->what == activateEvt */ )
  1013.         {
  1014.         HandleEvent(theEvent);
  1015.         }
  1016.  
  1017.     return false;
  1018.  
  1019. } // SaveDialogFilter
  1020.  
  1021.  
  1022. #if GENERATINGCFM
  1023.     static RoutineDescriptor gSaveDialogFilterRD = BUILD_ROUTINE_DESCRIPTOR(uppModalFilterYDProcInfo, SaveDialogFilter);
  1024.     static ModalFilterYDUPP gSaveDialogFilter = &gSaveDialogFilterRD;
  1025. #else
  1026.     static ModalFilterYDUPP gSaveDialogFilter = NewModalFilterYDProc(SaveDialogFilter);
  1027. #endif
  1028.  
  1029. // --------------------------------------------------------------------------------------------------------------
  1030.  
  1031. static OSErr    TextSaveAs(WindowRef pWindow, WindowDataPtr pData)
  1032. {
  1033.     OSErr                anErr = noErr;
  1034.     short                oldRes, oldData;
  1035.     StandardFileReply    sfReply;
  1036.     Boolean                documentIsText;
  1037.     
  1038.     // save the old references -- if there is an error, we restore them
  1039.     oldRes = pData->resRefNum;
  1040.     oldData = pData->dataRefNum;
  1041.     
  1042.     // ask where and how to save this document
  1043.     {
  1044.     Str255    defaultName;
  1045.     Point    where = {-1, -1};
  1046.     
  1047.     // setup for the call
  1048.     GetWTitle(pWindow, defaultName);
  1049.     SetCursor(&qd.arrow);
  1050.     
  1051.     // find out where the user wants the file
  1052.     CustomPutFile("\p", defaultName, &sfReply, 
  1053.                 kTextSaveAsDialogID, where,
  1054.                 gSaveDialogHook, gSaveDialogFilter, nil, nil, &documentIsText);
  1055.     
  1056.     // map the cancel button into a cancelling error
  1057.     if (!sfReply.sfGood)
  1058.         anErr = eUserCanceled;
  1059.     }
  1060.         
  1061.     // can't replace over other types    
  1062.     if (sfReply.sfReplacing)
  1063.         {
  1064.         FInfo    theInfo;
  1065.         
  1066.         FSpGetFInfo(&sfReply.sfFile, &theInfo);
  1067.         
  1068.         if ( (theInfo.fdType != 'TEXT') && (theInfo.fdType != 'sEXT') )
  1069.             anErr = eDocumentWrongKind;
  1070.         }
  1071.     nrequire(anErr, StandardPutFile);
  1072.         
  1073.     if     (
  1074.         (sfReply.sfReplacing) && 
  1075.         (oldData != -1) && 
  1076.         (pData->fileSpec.vRefNum == sfReply.sfFile.vRefNum) &&
  1077.         (pData->fileSpec.parID == sfReply.sfFile.parID) &&
  1078.         EqualString(pData->fileSpec.name, sfReply.sfFile.name, false, false)
  1079.         )
  1080.         {
  1081.  
  1082.         anErr = TextSave(pData);
  1083.         
  1084.         if (anErr == noErr)
  1085.             UpdateFileInfo(&sfReply.sfFile, documentIsText);
  1086.         }
  1087.     else
  1088.         {
  1089.         // create the data file and resource fork
  1090.         (void) FSpDelete(&sfReply.sfFile);
  1091.         anErr = FSpCreate(&sfReply.sfFile, 'ttxt', documentIsText ? 'TEXT' : 'sEXT', 0);
  1092.         FSpCreateResFile(&sfReply.sfFile, 'ttxt', documentIsText ? 'TEXT' : 'sEXT', 0);
  1093.         nrequire(anErr, FailedCreate);
  1094.  
  1095.         // set the stationary bit, if we must
  1096.         if (!documentIsText)
  1097.             {
  1098.             FInfo    theInfo;
  1099.             
  1100.             FSpGetFInfo(&sfReply.sfFile, &theInfo);
  1101.             theInfo.fdFlags |= kIsStationery;
  1102.             FSpSetFInfo(&sfReply.sfFile, &theInfo);
  1103.             }
  1104.  
  1105.         // open both of forks
  1106.         anErr = FSpOpenDF(&sfReply.sfFile, fsRdWrPerm, &pData->dataRefNum);
  1107.         if (anErr == noErr)
  1108.             {
  1109.             pData->resRefNum = FSpOpenResFile(&sfReply.sfFile, fsRdWrPerm);
  1110.             anErr = ResError();
  1111.             }
  1112.         nrequire(anErr, FailedOpen);
  1113.  
  1114.         // call the standard save function to do the save
  1115.         anErr = TextSave(pData);
  1116.     
  1117.     // FALL THROUGH EXCEPTION HANDLING
  1118.     FailedOpen:
  1119.         FSpDelete(&sfReply.sfFile);    
  1120.     FailedCreate:
  1121.     StandardPutFile:
  1122.  
  1123.         // finally, close the old files if everything went okay
  1124.         if (anErr == noErr)
  1125.             {
  1126.             if (oldRes != -1)
  1127.                 CloseResFile(oldRes);
  1128.             if (oldData != -1)
  1129.                 FSClose(oldData);
  1130.             pData->isWritable = true;
  1131.             SetWTitle(pWindow, sfReply.sfFile.name);
  1132.             }
  1133.         else
  1134.             {
  1135.             pData->resRefNum = oldRes;
  1136.             pData->dataRefNum = oldData;
  1137.             }
  1138.         }
  1139.     
  1140.     // save new location
  1141.     if (anErr == noErr)
  1142.         BlockMoveData(&sfReply.sfFile, &pData->fileSpec, sizeof(FSSpec));
  1143.         
  1144. // Return eUserCanceled so we can avoid closing/quitting if they cancel the SF dialog
  1145. //    // don't propagate this error
  1146. //    if (anErr == eUserCanceled)
  1147. //        anErr = noErr;
  1148.  
  1149.     return anErr;
  1150.     
  1151. } // TextSaveAs
  1152.  
  1153. // --------------------------------------------------------------------------------------------------------------
  1154. static void ApplyFace(short requestedFace, WindowRef pWindow, WindowDataPtr pData, short commandID)
  1155. {
  1156.     TextStyle    style;
  1157.     short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1158.     
  1159.     SaveCurrentUndoState(pData, commandID);
  1160.     
  1161.     style.tsFace = requestedFace;
  1162.     TESetStyle(doFace + ((requestedFace != normal) ? doToggle : 0), &style, true, ((TextDataPtr) pData)->hTE);
  1163.     TECalText(((TextDataPtr) pData)->hTE);
  1164.     
  1165.     oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1166.     AdjustTE(pData, false);
  1167.     AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1168.  
  1169.     pData->changed = true;
  1170.     
  1171. } // ApplyFace
  1172.  
  1173. // --------------------------------------------------------------------------------------------------------------
  1174. static OSErr ApplySize(short requestedSize, WindowRef pWindow, WindowDataPtr pData, short commandID)
  1175. {
  1176.     OSErr        anErr = noErr;
  1177.     TextStyle    style;
  1178.     short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1179.     
  1180.     SaveCurrentUndoState(pData, commandID);
  1181.  
  1182.     style.tsSize = requestedSize;
  1183.     TESetStyle(doSize, &style, true, ((TextDataPtr) pData)->hTE);
  1184.     TECalText(((TextDataPtr) pData)->hTE);
  1185.     if (CalculateTextEditHeight(((TextDataPtr) pData)->hTE) > 32767)
  1186.         {        
  1187.         style.tsSize = 0;
  1188.         TESetStyle(doSize, &style, true, ((TextDataPtr) pData)->hTE);
  1189.         anErr = eDocumentTooLarge;
  1190.         }
  1191.  
  1192.     oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1193.     AdjustTE(pData, false);
  1194.     AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1195.  
  1196.     pData->changed = true;
  1197.     
  1198.     return anErr;
  1199.  
  1200. } // ApplySize
  1201.  
  1202. // --------------------------------------------------------------------------------------------------------------
  1203. // OOP INTERFACE ROUTINES
  1204. // --------------------------------------------------------------------------------------------------------------
  1205.  
  1206. static OSErr    TextUpdateWindow(WindowRef pWindow, WindowDataPtr pData)
  1207. {
  1208.     Rect    updateArea = pData->contentRect;
  1209.     
  1210.     // be sure to also erase the area where the horizontal scroll bar
  1211.     // is missing.
  1212.     updateArea.bottom = GetWindowPort(pWindow)->portRect.bottom;
  1213.     EraseRect(&updateArea);
  1214.     
  1215.     TEUpdate(&pData->contentRect, ((TextDataPtr) pData)->hTE);
  1216.     
  1217.     DrawPictures(pData, ((TextDataPtr) pData)->hTE);
  1218.     
  1219.     DrawControls(pWindow);
  1220.     DrawGrowIcon(pWindow);
  1221.     
  1222.     return noErr;
  1223.     
  1224. } // TextUpdateWindow
  1225.  
  1226. // --------------------------------------------------------------------------------------------------------------
  1227.  
  1228. static OSErr    TextCloseWindow(WindowRef pWindow, WindowDataPtr pData)
  1229. {
  1230. #pragma unused (pWindow)
  1231.  
  1232.     // shut down text services
  1233.     if (pData->docTSMDoc)
  1234.         {
  1235.         FixTSMDocument(pData->docTSMDoc);
  1236.         DeactivateTSMDocument(pData->docTSMDoc);
  1237.         DeleteTSMDocument(pData->docTSMDoc);
  1238.         }
  1239.     
  1240.     DisposeOfSpeech(true);
  1241.     DisposeHandle(((TextDataPtr) pData)->soundHandle);
  1242.     TEDispose(((TextDataPtr) pData)->hTE);
  1243.  
  1244.     DisposeHandle(((TextDataPtr) pData)->prevText);
  1245.     DisposeHandle(((TextDataPtr) pData)->prevStyle);
  1246.     
  1247.     TextRemoveContentsMenu(pData);
  1248.  
  1249.     return noErr;
  1250.  
  1251. } // TextCloseWindow
  1252.  
  1253. // --------------------------------------------------------------------------------------------------------------
  1254.  
  1255. static OSErr    TextActivateEvent(WindowRef pWindow, WindowDataPtr pData, Boolean activating)
  1256. {
  1257. #pragma unused (pWindow)
  1258.  
  1259.     // only modifyable docs can be active
  1260.     if (pData->originalFileType == 'TEXT')
  1261.         {
  1262.         if (activating)
  1263.             {
  1264.             TEActivate(((TextDataPtr) pData)->hTE);
  1265.             if (pData->docTSMDoc != nil)
  1266.                 ActivateTSMDocument(pData->docTSMDoc);
  1267.             }
  1268.         else
  1269.             {
  1270.             TEDeactivate(((TextDataPtr) pData)->hTE);
  1271.             if (pData->docTSMDoc != nil)
  1272.                 DeactivateTSMDocument(pData->docTSMDoc);
  1273.             }
  1274.         }
  1275.         
  1276.     // add contents menu, if appropriate        
  1277.     if (activating)
  1278.         {
  1279.         TextAddContentsMenu(pData);
  1280.         }
  1281.     else
  1282.         {
  1283.         TextRemoveContentsMenu(pData);
  1284.         }
  1285.     
  1286.     return noErr;
  1287.     
  1288. } // TextActivateEvent
  1289.  
  1290. // --------------------------------------------------------------------------------------------------------------
  1291.  
  1292. static Boolean    TextFilterEvent(WindowRef pWindow, WindowDataPtr pData, EventRecord *pEvent)
  1293. {    
  1294.     switch (pEvent->what)
  1295.         {
  1296.         case nullEvent:
  1297.             if (pData->originalFileType == 'TEXT')
  1298.                 {
  1299.                 if ( pWindow == FrontWindow() )
  1300.                     TEIdle(((TextDataPtr) pData)->hTE);
  1301.                 }
  1302.                 
  1303.             // if we stop speaking, ditch the channel
  1304.             if (gSpeechChannel) 
  1305.                 {
  1306.                 SpeechStatusInfo    status;                // Status of our speech channel.
  1307.                 
  1308.                 if ( 
  1309.                     (GetSpeechInfo( gSpeechChannel, soStatus, (void*) &status ) == noErr)
  1310.                     &&  (!status.outputBusy )
  1311.                     )
  1312.                     DisposeOfSpeech(true);
  1313.                 }
  1314.             break;
  1315.         }
  1316.         
  1317.     return false;
  1318.     
  1319. } // TextFilterEvent
  1320.  
  1321. // --------------------------------------------------------------------------------------------------------------
  1322.  
  1323. static OSErr    TextScrollContent(WindowRef pWindow, WindowDataPtr pData, short deltaH, short deltaV)
  1324. {
  1325.     GrafPtr        port = (GrafPtr) GetWindowPort(pWindow);
  1326.     RgnHandle    srcRgn, dstRgn;
  1327.     Rect        viewRect;
  1328.     
  1329.     // scroll the text area
  1330.     TEScroll(deltaH, deltaV, ((TextDataPtr) pData)->hTE);
  1331.  
  1332.     // calculate the region that is uncovered by the scroll
  1333.     srcRgn = NewRgn();
  1334.     dstRgn = NewRgn();
  1335.     viewRect = (**((TextDataPtr) pData)->hTE).viewRect;
  1336.     RectRgn( srcRgn, &viewRect );
  1337.     SectRgn( srcRgn, port->visRgn,  srcRgn );
  1338.     SectRgn( srcRgn, port->clipRgn, srcRgn );
  1339.     CopyRgn( srcRgn, dstRgn );
  1340.     OffsetRgn( dstRgn, deltaH, deltaV );
  1341.     SectRgn( srcRgn, dstRgn, dstRgn );
  1342.     DiffRgn( srcRgn, dstRgn, srcRgn );
  1343.  
  1344.     // clip to this new area
  1345.     GetClip(dstRgn);
  1346.     SetClip(srcRgn);
  1347.         DrawPictures(pData, ((TextDataPtr) pData)->hTE);
  1348.     SetClip(dstRgn);
  1349.     
  1350.     // all done with these calculation regions
  1351.     DisposeRgn( srcRgn );
  1352.     DisposeRgn( dstRgn );
  1353.     
  1354.     return eActionAlreadyHandled;
  1355.     
  1356. } // TextScrollContent
  1357.  
  1358. // --------------------------------------------------------------------------------------------------------------
  1359.  
  1360. static OSErr    TextKeyEvent(WindowRef pWindow, WindowDataPtr pData, EventRecord *pEvent, Boolean isMotionKey)
  1361. {    
  1362.     OSErr    anErr = noErr;
  1363.     
  1364.     if (!(pEvent->modifiers & cmdKey)) 
  1365.         {
  1366.         char    theKey = pEvent->message & charCodeMask;
  1367.         char    theKeyCode = (pEvent->message >> 8) & charCodeMask;
  1368.         
  1369.         if ( ((theKey != kDeleteKey) || (theKeyCode != kForwardDeleteKey)) && 
  1370.             ((** ((TextDataPtr) pData)->hTE).teLength+1 > kMaxLength) )
  1371.             anErr = eDocumentTooLarge;
  1372.         else
  1373.             {
  1374.             long        oldHeight = CalculateTextEditHeight(((TextDataPtr) pData)->hTE);
  1375.             long        end = (**(((TextDataPtr) pData)->hTE)).selEnd;
  1376.             long        start = (**(((TextDataPtr) pData)->hTE)).selStart;
  1377.  
  1378.             ObscureCursor();
  1379.             SaveCurrentUndoState(pData, cTypingCommand);
  1380.             if (theKeyCode != kForwardDeleteKey)
  1381.                 {
  1382.                 if (pEvent->modifiers & shiftKey)
  1383.                     {
  1384.                     switch (theKeyCode)
  1385.                         {
  1386.                         case kUpArrow:
  1387.                             TEKey(theKey, ((TextDataPtr) pData)->hTE);
  1388.                             TESetSelect((**(((TextDataPtr) pData)->hTE)).selStart, end, ((TextDataPtr) pData)->hTE);
  1389.                             break;
  1390.                             
  1391.                         case kDownArrow:
  1392.                             TESetSelect(end, end, ((TextDataPtr) pData)->hTE);
  1393.                             TEKey(theKey, ((TextDataPtr) pData)->hTE);
  1394.                             TESetSelect(start, (**(((TextDataPtr) pData)->hTE)).selEnd, ((TextDataPtr) pData)->hTE);
  1395.                             break;
  1396.                             
  1397.                         case kRightArrow:
  1398.                             {
  1399.                             Handle textHandle = (**(((TextDataPtr) pData)->hTE)).hText;
  1400.                             Ptr textBuf;
  1401.                             char state;
  1402.                             
  1403.                             state = HGetState(textHandle);
  1404.                             HLock(textHandle);
  1405.                             textBuf = *(**(((TextDataPtr) pData)->hTE)).hText;
  1406.                             if (CharacterByteType(textBuf, start, smCurrentScript) != smSingleByte)
  1407.                                 ++end;
  1408.                             HSetState(textHandle, state);
  1409.                             TESetSelect(start, ++end, ((TextDataPtr) pData)->hTE);
  1410.                             }
  1411.                             break;
  1412.                             
  1413.                         case kLeftArrow:
  1414.                             if (start > 0)
  1415.                                 {
  1416.                                 if (start > 1)
  1417.                                     {
  1418.                                     Handle textHandle = (**(((TextDataPtr) pData)->hTE)).hText;
  1419.                                     Ptr textBuf;
  1420.                                     char state;
  1421.                                     
  1422.                                     state = HGetState(textHandle);
  1423.                                     HLock(textHandle);
  1424.                                     textBuf = *(**(((TextDataPtr) pData)->hTE)).hText;
  1425.                                     if (CharacterByteType(textBuf, start-1, smCurrentScript) != smSingleByte)
  1426.                                         --start;
  1427.                                     HSetState(textHandle, state);
  1428.                                     }
  1429.                                 TESetSelect(--start, end, ((TextDataPtr) pData)->hTE);
  1430.                                 }
  1431.                             break;
  1432.                             
  1433.                         default:
  1434.                             TEKey(theKey, ((TextDataPtr) pData)->hTE);
  1435.                         }
  1436.                     }
  1437.                 else
  1438.                     TEKey(theKey, ((TextDataPtr) pData)->hTE);
  1439.                 }
  1440.             else
  1441.                 {
  1442.                 if     (end < (**(((TextDataPtr) pData)->hTE)).teLength)
  1443.                     {
  1444.                     if (start == end)
  1445.                         TEKey(kRightArrowCharCode, ((TextDataPtr) pData)->hTE);
  1446.                     TEKey(kBackspaceCharCode, ((TextDataPtr) pData)->hTE);
  1447.                     }
  1448.                 }
  1449.             oldHeight -= CalculateTextEditHeight(((TextDataPtr) pData)->hTE);
  1450.                             
  1451.             ((TextDataPtr) pWindow)->insideClickLoop = true;
  1452.                 AdjustTE(pData, false);
  1453.                 AdjustScrollBars(pWindow, (oldHeight > 0), (oldHeight > 0), nil);
  1454.             ((TextDataPtr) pWindow)->insideClickLoop = false;
  1455.  
  1456.             if (!isMotionKey)
  1457.                 pData->changed = true;
  1458.             }
  1459.         }
  1460.  
  1461.     return anErr;
  1462.  
  1463. } // TextKeyEvent
  1464.  
  1465. // --------------------------------------------------------------------------------------------------------------
  1466.  
  1467. static OSErr    TextContentClick(WindowRef pWindow, WindowDataPtr pData, EventRecord *pEvent)
  1468. {
  1469.     OSErr            anErr = noErr;
  1470.     Point            clickPoint = pEvent->where;
  1471.     ControlHandle    theControl;
  1472.     RgnHandle        hilightRgn;
  1473.  
  1474.     GlobalToLocal(&clickPoint);
  1475.     if (FindControl(clickPoint, pWindow, &theControl) == 0)
  1476.         {
  1477.         if (gMachineInfo.haveDragMgr)
  1478.             {
  1479.             hilightRgn = NewRgn();
  1480.             TEGetHiliteRgn(hilightRgn, ((TextDataPtr) pData)->hTE);
  1481.     
  1482.             if (PtInRgn(clickPoint, hilightRgn))
  1483.                 {
  1484.                 SaveCurrentUndoState(pData, cTypingCommand);
  1485.                 if (!DragText(pWindow, pData, pEvent, hilightRgn))
  1486.                     anErr = eActionAlreadyHandled;
  1487.                 }
  1488.             else        
  1489.                 {
  1490.                 anErr = eActionAlreadyHandled;
  1491.                 }
  1492.     
  1493.             DisposeRgn(hilightRgn);
  1494.             }
  1495.         else
  1496.             {
  1497.             anErr = eActionAlreadyHandled;
  1498.             }
  1499.         }
  1500.  
  1501.     if ( (anErr == eActionAlreadyHandled) && (PtInRect(clickPoint, &pData->contentRect)) )
  1502.         {
  1503.         TEClick(clickPoint, (pEvent->modifiers & shiftKey) != 0, ((TextDataPtr) pData)->hTE);
  1504.         }
  1505.         
  1506.     return anErr;
  1507.     
  1508. } // TextContentClick
  1509.  
  1510. // --------------------------------------------------------------------------------------------------------------
  1511.  
  1512. static OSErr    TextAdjustSize(WindowRef pWindow, WindowDataPtr pData, 
  1513.             Boolean *didReSize) // input: was window resized, output: t->we resized something
  1514. {
  1515. #pragma unused (pWindow)
  1516.     
  1517.     if (*didReSize)
  1518.         {
  1519.         RecalcTE(pData, true);
  1520.         AdjustTE(pData, true);
  1521.         }
  1522.     else
  1523.         {
  1524.         AdjustTE(pData, false);
  1525.         }
  1526.         
  1527.     return noErr;
  1528.     
  1529. } // TextAdjustSize
  1530.  
  1531. // --------------------------------------------------------------------------------------------------------------
  1532.  
  1533. static OSErr    TextCommand(WindowRef pWindow, WindowDataPtr pData, short commandID, long menuResult)
  1534. {
  1535.  
  1536.     OSErr    anErr = noErr;
  1537.     
  1538.     SetPort((GrafPtr) GetWindowPort(pWindow));
  1539.     
  1540.     if ( (pData->docTSMDoc) && (menuResult != 0) )
  1541.         FixTSMDocument(pData->docTSMDoc);
  1542.         
  1543.     switch (commandID)
  1544.         {            
  1545.         case cUndo:
  1546.             {
  1547.             short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1548.  
  1549.             PerformUndo(pData);
  1550.             oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1551.             AdjustTE(pData, false);
  1552.             AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1553.             RecalcTE(pData, true);
  1554.             pData->changed = true;
  1555.             }
  1556.             break;
  1557.             
  1558.         case cCut:
  1559.             SaveCurrentUndoState(pData, cCut);
  1560.             {
  1561.             short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1562.  
  1563.             TECut(((TextDataPtr) pData)->hTE);    // no need for TEToScrap with styled TE record
  1564.             oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1565.             AdjustTE(pData, false);
  1566.             AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1567.             pData->changed = true;
  1568.             }
  1569.             break;
  1570.             
  1571.         case cCopy:
  1572.             TECopy(((TextDataPtr) pData)->hTE);    // no need for TEToScrap with styled TE record
  1573.             AdjustTE(pData, false);
  1574.             break;
  1575.             
  1576.         case cClear:
  1577.             SaveCurrentUndoState(pData, cClear);
  1578.             {
  1579.             short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1580.  
  1581.             TEDelete(((TextDataPtr) pData)->hTE);
  1582.             oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1583.             AdjustTE(pData, false);
  1584.             AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1585.             pData->changed = true;
  1586.             }
  1587.             break;
  1588.             
  1589.         case cPaste:
  1590.             SaveCurrentUndoState(pData, cPaste);
  1591.             {
  1592.             short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1593.  
  1594.             anErr = TEFromScrap();            
  1595.             if (anErr == noErr)
  1596.                 {                
  1597.                 // if the current length, plus the paste data, minus the data in the selection
  1598.                 // would make the document too large, say so
  1599.                 if     ( 
  1600.                         ((** ((TextDataPtr) pData)->hTE).teLength +
  1601.                         TEGetScrapLength() -
  1602.                         ((** ((TextDataPtr) pData)->hTE).selEnd-(** ((TextDataPtr) pData)->hTE).selStart)
  1603.                         )
  1604.                     > kMaxLength)
  1605.                     {
  1606.                     anErr = eDocumentTooLarge;
  1607.                     }
  1608.                 else
  1609.                     {
  1610.                     Handle    aHandle = (Handle) TEGetText(((TextDataPtr) pData)->hTE);
  1611.                     Size    oldSize = GetHandleSize(aHandle);
  1612.                     Size    newSize = oldSize + TEGetScrapLength();
  1613.                     OSErr    saveErr;
  1614.                     
  1615.                     SetHandleSize(aHandle, newSize);
  1616.                     saveErr = MemError();
  1617.                     SetHandleSize(aHandle, oldSize);
  1618.                     if (saveErr != noErr)
  1619.                         anErr = eDocumentTooLarge;
  1620.                     else
  1621.                         TEStylePaste(((TextDataPtr) pData)->hTE);
  1622.                     }
  1623.                     
  1624.                 UnloadScrap();
  1625.                 }
  1626.             oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1627.             AdjustTE(pData, false);
  1628.             AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1629.             pData->changed = true;
  1630.             }
  1631.             break;
  1632.             
  1633.         case cReplace:
  1634.             SaveCurrentUndoState(pData, cReplace);
  1635.             {
  1636.             short result = ConductFindOrReplaceDialog(kReplaceWindowID);
  1637.             
  1638.             if (result == cancel)
  1639.                 break;
  1640.                 
  1641.             if (result == iReplaceAll)
  1642.                 {
  1643.                 long         newStart, newEnd;
  1644.                 short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1645.                 
  1646.                 TESetSelect(0, 0, ((TextDataPtr) pData)->hTE);
  1647.                 while (PerformSearch((**((TextDataPtr) pData)->hTE).hText,
  1648.                                     (**((TextDataPtr) pData)->hTE).selStart,
  1649.                                     gFindString, gCaseSensitive, false, false,
  1650.                                     &newStart, &newEnd))
  1651.                     {
  1652.                     TESetSelect(newStart, newEnd, ((TextDataPtr) pData)->hTE);
  1653.                     TEDelete(((TextDataPtr) pData)->hTE);
  1654.                     TEInsert(&gReplaceString[1], gReplaceString[0], ((TextDataPtr) pData)->hTE);
  1655.                     TESetSelect(newStart, newStart+gReplaceString[0], ((TextDataPtr) pData)->hTE);                
  1656.                     pData->changed = true;
  1657.                     }
  1658.                 oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1659.                 
  1660.                 AdjustTE(pData, false);
  1661.                 AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1662.     
  1663.                 anErr = eActionAlreadyHandled;
  1664.                 break;
  1665.                 }
  1666.             }
  1667.         
  1668.         // fall through from replace
  1669.         case cReplaceAgain:
  1670.             SaveCurrentUndoState(pData, cReplaceAgain);
  1671.             {
  1672.             long     newStart, newEnd;
  1673.             Boolean    isBackwards = ((gEvent.modifiers & shiftKey) != 0);
  1674.             
  1675.             if (PerformSearch((**((TextDataPtr) pData)->hTE).hText,
  1676.                                 isBackwards ? (**((TextDataPtr) pData)->hTE).selEnd : (**((TextDataPtr) pData)->hTE).selStart,
  1677.                                 gFindString, gCaseSensitive, isBackwards, gWrapAround,
  1678.                                 &newStart, &newEnd))
  1679.                 {
  1680.                 short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1681.                 
  1682.                 TESetSelect(newStart, newEnd, ((TextDataPtr) pData)->hTE);
  1683.                 TEDelete(((TextDataPtr) pData)->hTE);
  1684.                 TEInsert(&gReplaceString[1], gReplaceString[0], ((TextDataPtr) pData)->hTE);
  1685.                 TESetSelect(newStart, newStart+gReplaceString[0], ((TextDataPtr) pData)->hTE);                
  1686.                 oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1687.                 
  1688.                 AdjustTE(pData, false);
  1689.                 AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1690.                 pData->changed = true;
  1691.                 }
  1692.             else
  1693.                 SysBeep(1);
  1694.  
  1695.             anErr = eActionAlreadyHandled;
  1696.             }
  1697.             break;
  1698.             
  1699.         case cFind:
  1700.         case cFindSelection:
  1701.             if (commandID == cFind)
  1702.                 {
  1703.                 if (ConductFindOrReplaceDialog(kFindWindowID) == cancel)    
  1704.                     break;
  1705.                 }
  1706.             else
  1707.                 {
  1708.                 gFindString[0] = (**((TextDataPtr) pData)->hTE).selEnd - (**((TextDataPtr) pData)->hTE).selStart;
  1709.                 BlockMoveData( (*(**((TextDataPtr) pData)->hTE).hText) + (**((TextDataPtr) pData)->hTE).selStart, &gFindString[1], gFindString[0]);
  1710.                 }
  1711.             
  1712.         // fall through from find or find selection
  1713.         case cFindAgain:
  1714.             {
  1715.             long     newStart, newEnd;
  1716.             Boolean    isBackwards = ((gEvent.modifiers & shiftKey) != 0);
  1717.             
  1718.             if (PerformSearch((**((TextDataPtr) pData)->hTE).hText,
  1719.                                 isBackwards ? (**((TextDataPtr) pData)->hTE).selStart : (**((TextDataPtr) pData)->hTE).selEnd,
  1720.                                 gFindString, gCaseSensitive, isBackwards, gWrapAround,
  1721.                                 &newStart, &newEnd))
  1722.                 {
  1723.                 TESetSelect(newStart, newEnd, ((TextDataPtr) pData)->hTE);
  1724.                 AdjustTE(pData, false);
  1725.                 AdjustScrollBars(pWindow, false, false, nil);
  1726.                 }
  1727.             else
  1728.                 SysBeep(1);
  1729.  
  1730.             anErr = eActionAlreadyHandled;
  1731.             }
  1732.             break;
  1733.             
  1734.         case cSelectAll:
  1735.             TESetSelect(0, (**((TextDataPtr) pData)->hTE).teLength, 
  1736.                         ((TextDataPtr) pData)->hTE);
  1737.             AdjustTE(pData, false);
  1738.             AdjustScrollBars(pWindow, false, false, nil);
  1739.             anErr = eActionAlreadyHandled;
  1740.             break;
  1741.         
  1742.         // save turns into save as if this is a new document or if the original wasn't
  1743.         // available for writing
  1744.         case cSave:
  1745.             if     (
  1746.                 (!pData->isWritable) || 
  1747.                 ( (pData->dataRefNum == -1) && (pData->resRefNum == -1) )
  1748.                 )
  1749.                 anErr = TextSaveAs(pWindow, pData);
  1750.             else
  1751.                 anErr = TextSave(pData);
  1752.             break;
  1753.             
  1754.         case cSaveAs:
  1755.             anErr = TextSaveAs(pWindow, pData);
  1756.             break;
  1757.             
  1758.         // SUPPORTED FONTS
  1759. //        case cSelectFontStyle:            
  1760.         case cSelectFont:
  1761.             SaveCurrentUndoState(pData, cSelectFont);
  1762.             {
  1763.             Str255        itemName;
  1764.             Str255        menuName;
  1765.             TextStyle    theStyle;
  1766.             short        oldNumLines = (**(((TextDataPtr) pData)->hTE)).nLines;
  1767.             
  1768.             GetMenuItemText( GetMenuHandle( menuResult>>16 ), menuResult & 0xFFFF, itemName );
  1769.             GetFNum( itemName, &theStyle.tsFont );
  1770.                     
  1771.             TESetStyle( doFont, &theStyle, true, ((TextDataPtr) pData)->hTE );
  1772.                 
  1773.             TECalText(((TextDataPtr) pData)->hTE);
  1774.             oldNumLines -= (**(((TextDataPtr) pData)->hTE)).nLines;
  1775.             AdjustTE(pData, false);
  1776.             AdjustScrollBars(pWindow, (oldNumLines > 0), (oldNumLines > 0), nil);
  1777.             pData->changed = true;
  1778.             }
  1779.             break;
  1780.             
  1781.             
  1782.         // SUPPORTED STYLES
  1783.         case cPlain:
  1784.             ApplyFace(normal, pWindow, pData, cPlain);
  1785.             break;
  1786.             
  1787.         case cBold:
  1788.             ApplyFace(bold, pWindow, pData, cBold);
  1789.             break;
  1790.  
  1791.         case cItalic:
  1792.             ApplyFace(italic, pWindow, pData, cItalic);
  1793.             break;
  1794.             
  1795.         case cUnderline:
  1796.             ApplyFace(underline, pWindow, pData, cUnderline);
  1797.             break;
  1798.             
  1799.         case cOutline:
  1800.             ApplyFace(outline, pWindow, pData, cOutline);
  1801.             break;
  1802.             
  1803.         case cShadow:
  1804.             ApplyFace(shadow, pWindow, pData, cShadow);
  1805.             break;
  1806.  
  1807.         case cCondensed:
  1808.             ApplyFace(condense, pWindow, pData, cCondensed);
  1809.             break;
  1810.             
  1811.         case cExtended:
  1812.             ApplyFace(extend, pWindow, pData, cExtended);
  1813.             break;
  1814.             
  1815.     
  1816.         // SUPPORTED SIZES
  1817.         case cSize9:
  1818.             anErr = ApplySize(9, pWindow, pData, cSize9);
  1819.             break;
  1820.             
  1821.         case cSize10:
  1822.             anErr = ApplySize(10, pWindow, pData, cSize10);
  1823.             break;
  1824.             
  1825.         case cSize12:
  1826.             anErr = ApplySize(12, pWindow, pData, cSize12);
  1827.             break;
  1828.             
  1829.         case cSize14:
  1830.             anErr = ApplySize(14, pWindow, pData, cSize14);
  1831.             break;
  1832.             
  1833.         case cSize18:
  1834.             anErr = ApplySize(18, pWindow, pData, cSize18);
  1835.             break;
  1836.             
  1837.         case cSize24:
  1838.             anErr = ApplySize(24, pWindow, pData, cSize24);
  1839.             break;
  1840.             
  1841.         case cSize36:
  1842.             anErr = ApplySize(36, pWindow, pData, cSize36);
  1843.             break;
  1844.             
  1845.             
  1846.         // SUPPORTED SOUND COMMANDS
  1847.         case cRecord:
  1848.             {
  1849.             Handle    tempHandle;
  1850.  
  1851.             // allocate our prefered buffer if we can, but if we can't
  1852.             // make sure that at least a minimum amount of RAM is around
  1853.             // before recording.
  1854.             tempHandle = NewHandle(kPrefBufferSize);
  1855.             anErr = MemError();
  1856.             if (anErr != noErr)
  1857.                 {
  1858.                 tempHandle = NewHandle(kMinBufferSize);
  1859.                 anErr = MemError();
  1860.                 DisposeHandle(tempHandle);
  1861.                 tempHandle = nil;
  1862.                 }
  1863.             
  1864.             // if the preflight goes okay, do the record
  1865.             if (anErr == noErr)
  1866.                 {
  1867.                 Point    where = {50, 100};
  1868.                 
  1869.                 anErr = SndRecord(nil, where, siGoodQuality, (SndListHandle*) &tempHandle);
  1870.                 if (anErr == noErr)
  1871.                     {
  1872.                     DisposeHandle(((TextDataPtr) pData)->soundHandle);
  1873.                     ((TextDataPtr) pData)->soundHandle = tempHandle;
  1874.                     pData->changed = true;
  1875.                     }
  1876.                 else
  1877.                     DisposeHandle(tempHandle);
  1878.                     
  1879.                 if (anErr == userCanceledErr)
  1880.                     anErr = noErr;
  1881.                 }
  1882.             }
  1883.             break;
  1884.             
  1885.         case cPlay:
  1886.             if (((TextDataPtr) pData)->soundHandle)
  1887.                 (void) SndPlay(nil, (SndListHandle) ((TextDataPtr) pData)->soundHandle, false);
  1888.             break;
  1889.  
  1890.         case cErase:
  1891.             DisposeHandle(((TextDataPtr) pData)->soundHandle);
  1892.             ((TextDataPtr) pData)->soundHandle = nil;
  1893.             pData->changed = true;
  1894.             break;
  1895.             
  1896.         case cSpeak:
  1897.             DisposeOfSpeech(false);
  1898.             if (gSpeechChannel == nil)
  1899.                 anErr = NewSpeechChannel( &gCurrentVoice, &gSpeechChannel );
  1900.                 
  1901.             if ( anErr == noErr )
  1902.                 {
  1903.                 short    textLength, textStart;
  1904.                                     
  1905.                 // determine which text to speak
  1906.                 if ( (**((TextDataPtr) pData)->hTE).selEnd > (**((TextDataPtr) pData)->hTE).selStart )    // If there is a selection.
  1907.                     {
  1908.                     textLength = (**((TextDataPtr) pData)->hTE).selEnd - (**((TextDataPtr) pData)->hTE).selStart;
  1909.                     textStart = (**((TextDataPtr) pData)->hTE).selStart;
  1910.                     }
  1911.                 else                                            // No text selected.
  1912.                     {
  1913.                     textLength = (**((TextDataPtr) pData)->hTE).teLength;
  1914.                     textStart = 0;
  1915.                     }
  1916.                     
  1917.                     
  1918.                 gSpeakPtr = NewPtr(textLength);
  1919.                 anErr = MemError();
  1920.                 if (anErr == noErr)
  1921.                     {
  1922.                     BlockMoveData( *((**((TextDataPtr) pData)->hTE).hText) + textStart, gSpeakPtr, (Size) textLength );
  1923.                     anErr = SpeakText( gSpeechChannel, gSpeakPtr, textLength );
  1924.                     }
  1925.                 }
  1926.             break;
  1927.  
  1928.         case cStopSpeaking:
  1929.             DisposeOfSpeech(true);
  1930.             break;
  1931.             
  1932.         case cSelectVoiceSubMenu:
  1933.                 {
  1934.                 VoiceSpec    newSpec;
  1935.                 short        i, menuIndex;
  1936.                 Str255        itemText;
  1937.                 short        theVoiceCount;
  1938.                 MenuHandle     menu = GetMenuHandle(mVoices);
  1939.                 
  1940.                 // in order to change voices, we need to ditch the speaking
  1941.                 DisposeOfSpeech(true);
  1942.  
  1943.                 // get the name of the selected voice                
  1944.                 menuIndex = menuResult & 0xFFFF;
  1945.                 GetMenuItemText(menu, menuIndex, itemText);
  1946.                 
  1947.                 if (CountVoices( &theVoiceCount ) == noErr)
  1948.                     {
  1949.                     VoiceDescription    description;        // Info about a voice.
  1950.         
  1951.                     for (i = 1; i <= theVoiceCount; ++i)
  1952.                         {
  1953.                         if ( (GetIndVoice( i, &newSpec ) == noErr)  &&
  1954.                              (GetVoiceDescription( &newSpec, &description, sizeof(description) ) == noErr ) )
  1955.                             {
  1956.                             if (IUCompString( itemText, description.name ) == 0)
  1957.                                 break;
  1958.                             }
  1959.                         }
  1960.                     }
  1961.                     
  1962.                 gCurrentVoice = newSpec;
  1963.                 for (i = CountMItems(menu); i >= 1; --i)
  1964.                     CheckItem(menu, i, (menuIndex == i));
  1965.                 }
  1966.             break;
  1967.         
  1968.         
  1969.         case cSelectContents:
  1970.                 {
  1971.                 Str255    searchStr;
  1972.                 short    menuIndex;
  1973.                 long     newStart, newEnd;
  1974.                 
  1975.                 menuIndex = menuResult & 0xFFFF;
  1976.  
  1977.                 // get the search string for this menu item
  1978.                 anErr = TextGetContentsListItem(pData, menuIndex, nil, searchStr, nil);
  1979.                 
  1980.                 if (anErr == noErr)
  1981.                     {
  1982.                     if (PerformSearch(
  1983.                         (**((TextDataPtr) pData)->hTE).hText,
  1984.                         0,            // start at beginning of text
  1985.                         searchStr,
  1986.                         false,        // not case sensitive
  1987.                         false,        // forwards
  1988.                         false,        // wrap
  1989.                         &newStart, 
  1990.                         &newEnd))
  1991.                         {
  1992.                         
  1993.                         // <7>
  1994.                         
  1995.                         short     amount;
  1996.                         Point    newSelectionPt;
  1997.                         
  1998.                         // get QuickDraw offset of found text,  
  1999.                         // scroll that amount plus a line height,
  2000.                         // and add a fifth of the window for aesthetics (and  
  2001.                         // for slop to avoid fraction-of-line problems)
  2002.  
  2003.                         newSelectionPt = TEGetPoint(newEnd, ((TextDataPtr) pData)->hTE);
  2004.                         
  2005.                         amount = - newSelectionPt.v + pData->vScrollAmount;
  2006.                         amount += (pData->contentRect.bottom - pData->contentRect.top) / 5;
  2007.                         
  2008.                         SetControlAndClipAmount(pData->vScroll, &amount);
  2009.                         if (amount != 0)
  2010.                             {
  2011.                             DoScrollContent(pWindow, pData, 0, amount);
  2012.                             }
  2013.  
  2014.                         // move selection to beginning of found text 
  2015.                         // (are the Adjust calls necessary?)
  2016.                         
  2017.                         TESetSelect(newStart, newStart, ((TextDataPtr) pData)->hTE);    
  2018.                         AdjustTE(pData, false);
  2019.                         AdjustScrollBars(pWindow, false, false, nil);
  2020.  
  2021.                         }
  2022.                     else
  2023.                         {
  2024.                             // search failed
  2025.                             SysBeep(10);
  2026.                         }
  2027.                     }
  2028.                 }
  2029.             break;
  2030.         }
  2031.         
  2032.     return anErr;
  2033.     
  2034. } // TextCommand
  2035.  
  2036. // --------------------------------------------------------------------------------------------------------------
  2037.  
  2038. static OSErr    TextAdjustMenus(WindowRef pWindow, WindowDataPtr pData)
  2039. {
  2040. #pragma unused (pWindow)
  2041.  
  2042.     // enable the commands that we support for editable text document
  2043.     if (pData->originalFileType == 'TEXT')
  2044.         {        
  2045.         if (((TextDataPtr) pData)->prevCommandID != cNull)
  2046.             EnableCommand(cUndo);
  2047.             
  2048.         if ( (**((TextDataPtr) pData)->hTE).selEnd > (**((TextDataPtr) pData)->hTE).selStart )    // If there is a selection.
  2049.             {
  2050.             EnableCommand(cCut);
  2051.             EnableCommand(cCopy);
  2052.             EnableCommand(cClear);
  2053.             
  2054.             EnableCommand(cFindSelection);
  2055.             }
  2056.         
  2057.         TEFromScrap();
  2058.         if (TEGetScrapLength() > 0)
  2059.             EnableCommand(cPaste);
  2060.             
  2061.         EnableCommand(cSaveAs);
  2062.         EnableCommand(cSelectAll);
  2063.         
  2064.         EnableCommand(cFind);
  2065.         EnableCommand(cReplace);
  2066.         if (gFindString[0] != 0)
  2067.             {
  2068.             EnableCommand(cFindAgain);
  2069.             EnableCommand(cReplaceAgain);
  2070.             }
  2071.             
  2072.         // enable all fonts, select the font current, if that's what's best
  2073.         EnableCommand(cSelectFont);
  2074.         {
  2075.         short        mode = doFont;
  2076.         Str255        fontName, itemName;
  2077.         Str255        styleName;
  2078.         TextStyle    theStyle;
  2079.         Boolean        isCont;
  2080.         
  2081.         isCont = TEContinuousStyle(&mode, &theStyle, ((TextDataPtr) pData)->hTE);
  2082.         if (isCont)
  2083.             {
  2084.             GetFontName(theStyle.tsFont, fontName);
  2085.             }
  2086.  
  2087.  
  2088.             {
  2089.             MenuHandle    menu = GetMenuHandle( mFont );
  2090.             short        count = CountMItems(menu);
  2091.             short        index;
  2092.             
  2093.             for (index = 1; index <= count; ++index)
  2094.                 {
  2095.                 short    mark;
  2096.                 
  2097.                 GetItemMark(menu, index, &mark);
  2098.                 if (isCont)
  2099.                     {
  2100.                     GetMenuItemText( menu, index, itemName );
  2101.                     
  2102.                     // don't change the checkmark if it's a heirarchichal menu, because
  2103.                     // the mark actually holds the ID of sub-menu
  2104.                     if ((mark == noMark) || (mark == checkMark))
  2105.                         {
  2106.                         CheckItem(menu, index, EqualString(itemName, fontName, true, true) );
  2107.                         }
  2108.                     else
  2109.                         {
  2110.                         // if it is a sub menu, we check there too
  2111.                         MenuHandle    subMenu = GetMenuHandle(mark);
  2112.                         short        subCount = CountMItems(subMenu);
  2113.                         short        subIndex;
  2114.                         
  2115.                         if (EqualString(itemName, fontName, true, true))
  2116.                             {
  2117.                             SetItemStyle(menu, index, underline);
  2118.                             for (subIndex = 1; subIndex <= subCount; ++subIndex)
  2119.                                 {
  2120.                                 GetMenuItemText(subMenu, subIndex, itemName);
  2121.                                 CheckItem(subMenu, subIndex, EqualString(itemName, styleName, true, true) );
  2122.                                 }
  2123.                             }
  2124.                         else
  2125.                             {
  2126.                             SetItemStyle(menu, index, normal);
  2127.                             for (subIndex = 1; subIndex <= subCount; ++subIndex)
  2128.                                 CheckItem(subMenu, subIndex, false );
  2129.                             }
  2130.                         }
  2131.                     }
  2132.                 else
  2133.                     {
  2134.                     if ((mark == noMark) || (mark == checkMark))
  2135.                         CheckItem(menu, index, false);
  2136.                     else
  2137.                         SetItemStyle(menu, index, normal);
  2138.                     }
  2139.                 }
  2140.             }
  2141.         }
  2142.  
  2143.         // enable the sizes, and outline what's currently valid
  2144.         {
  2145.         short        mode;
  2146.         TextStyle    theStyle;
  2147.         Boolean        isCont;
  2148.         short        whichToCheck;
  2149.         
  2150.         // find out the continuous run of sizes
  2151.         whichToCheck = 0;
  2152.         mode = doSize;
  2153.         if (TEContinuousStyle(&mode, &theStyle, ((TextDataPtr) pData)->hTE))
  2154.             {            
  2155.             whichToCheck = theStyle.tsSize;
  2156.             
  2157.             // default font size -> proper size
  2158.             if (whichToCheck == 0)
  2159.                 whichToCheck = GetDefFontSize();
  2160.             }
  2161.             
  2162.         // find out the font runs
  2163.         mode = doFont;
  2164.         isCont = TEContinuousStyle(&mode, &theStyle, ((TextDataPtr) pData)->hTE);
  2165.         
  2166.         EnableCommandCheckStyle(cSize9,  whichToCheck == 9, (isCont & RealFont(theStyle.tsFont, 9)) ? outline : normal);
  2167.         EnableCommandCheckStyle(cSize10, whichToCheck == 10, (isCont & RealFont(theStyle.tsFont, 10)) ? outline : normal);
  2168.         EnableCommandCheckStyle(cSize12, whichToCheck == 12, (isCont & RealFont(theStyle.tsFont, 12)) ? outline : normal);
  2169.         EnableCommandCheckStyle(cSize14, whichToCheck == 14, (isCont & RealFont(theStyle.tsFont, 14)) ? outline : normal);
  2170.         EnableCommandCheckStyle(cSize18, whichToCheck == 18, (isCont & RealFont(theStyle.tsFont, 18)) ? outline : normal);
  2171.         EnableCommandCheckStyle(cSize24, whichToCheck == 24, (isCont & RealFont(theStyle.tsFont, 24)) ? outline : normal);
  2172.         EnableCommandCheckStyle(cSize36, whichToCheck == 36, (isCont & RealFont(theStyle.tsFont, 36)) ? outline : normal);            
  2173.         }
  2174.         
  2175.         {
  2176.         short        mode = doFace;
  2177.         TextStyle    theStyle;
  2178.         Style        legalStyles;
  2179.         
  2180.         if (!TEContinuousStyle(&mode, &theStyle, ((TextDataPtr) pData)->hTE))
  2181.             {
  2182.             theStyle.tsFace = normal;
  2183.             EnableCommandCheck(cPlain, false);
  2184.             }
  2185.         else
  2186.             EnableCommandCheck(cPlain, theStyle.tsFace == normal);
  2187.             
  2188.         // <39> use the script manager to determine legal styles for this
  2189.         // run of text.  If the legal styles are zero (trap unimplemented),
  2190.         // then we assume all styles.
  2191.         legalStyles = GetScriptVariable(GetScriptManagerVariable(smKeyScript), smScriptValidStyles);
  2192.         if (legalStyles == 0)
  2193.             legalStyles = 0xFFFF;
  2194.             
  2195.         if (legalStyles & bold)
  2196.             EnableCommandCheck(cBold,             theStyle.tsFace & bold);
  2197.         if (legalStyles & italic)
  2198.             EnableCommandCheck(cItalic,         theStyle.tsFace & italic);
  2199.         if (legalStyles & underline)
  2200.             EnableCommandCheck(cUnderline,         theStyle.tsFace & underline);
  2201.         if (legalStyles & outline)
  2202.             EnableCommandCheck(cOutline,         theStyle.tsFace & outline);
  2203.         if (legalStyles & shadow)
  2204.             EnableCommandCheck(cShadow,         theStyle.tsFace & shadow);
  2205.         if (legalStyles & condense)
  2206.             EnableCommandCheck(cCondensed,         theStyle.tsFace & condense);
  2207.         if (legalStyles & extend)
  2208.             EnableCommandCheck(cExtended,         theStyle.tsFace & extend);
  2209.         }
  2210.         
  2211.         }
  2212.  
  2213.     // enable commands related to speaking the content if we have support for that
  2214.     if (gMachineInfo.haveTTS)
  2215.         {
  2216.         // if we are speaking, we can stop
  2217.         if (gSpeechChannel) 
  2218.             EnableCommand(cStopSpeaking);
  2219.  
  2220.         // even while speaking, you can re-speak or select a new voice
  2221.         EnableCommand(cSpeak);
  2222.         EnableCommand(cSelectVoice);
  2223.         EnableCommand(cSelectVoiceSubMenu);
  2224.         
  2225.         if ( (**((TextDataPtr) pData)->hTE).selEnd > (**((TextDataPtr) pData)->hTE).selStart )    // If there is a selection.
  2226.             ChangeCommandName(cSpeak, kTextStrings, iSpeakSelection);
  2227.         else
  2228.             ChangeCommandName(cSpeak, kTextStrings, iSpeakAll);
  2229.             
  2230.         }
  2231.         
  2232.     // enable the correct controls to go with sound input/output
  2233.     if (((TextDataPtr) pData)->soundHandle)
  2234.         EnableCommand(cPlay);
  2235.     if (pData->originalFileType == 'TEXT')
  2236.         {
  2237.         if (((TextDataPtr) pData)->soundHandle)
  2238.             EnableCommand(cErase);
  2239.         else
  2240.             {
  2241.             if (gMachineInfo.haveRecording)
  2242.                 EnableCommand(cRecord);
  2243.             }
  2244.         }
  2245.     
  2246.     // enable the contents menu, if any         
  2247.     (void) TextAdjustContentsMenu(pData);
  2248.     
  2249.     // enable commands that we support at all times
  2250.     if (GetControlMaximum(pData->vScroll) != 0)
  2251.         {
  2252.         EnableCommand(cNextPage);
  2253.         EnableCommand(cPreviousPage);
  2254.         }
  2255.     
  2256.     return noErr;
  2257.     
  2258. } // TextAdjustMenus
  2259.  
  2260. // --------------------------------------------------------------------------------------------------------------
  2261.  
  2262. static OSErr    TextGetDocumentRect(WindowRef pWindow, WindowDataPtr pData, 
  2263.             LongRect * documentRectangle, Boolean forGrow)
  2264. {
  2265. #pragma unused (pWindow)
  2266.     
  2267.     Rect    theRect = pData->contentRect;
  2268.     Rect    maxRect = (**GetGrayRgn()).rgnBBox;
  2269.     
  2270.     if ( (!forGrow) && (!(((TextDataPtr) pData)->insideClickLoop) ) )
  2271.         RecalcTE(pData, false);
  2272.     
  2273.     theRect.bottom = CalculateTextEditHeight(((TextDataPtr) pData)->hTE);
  2274.     theRect.bottom += kMargins*2;
  2275.     theRect.right = maxRect.right;
  2276.         
  2277.     if (theRect.bottom < pData->contentRect.bottom)
  2278.         theRect.bottom = pData->contentRect.bottom;
  2279.         
  2280.     if (forGrow)
  2281.         theRect.bottom = maxRect.bottom-kScrollBarSize;
  2282.         
  2283.     RectToLongRect(&theRect, documentRectangle);
  2284.     
  2285.     return noErr;
  2286.     
  2287. } // TextGetDocumentRect
  2288.  
  2289. // --------------------------------------------------------------------------------------------------------------
  2290.  
  2291. static OSErr    TextGetBalloon(WindowRef pWindow, WindowDataPtr pData, 
  2292.         Point *localMouse, short * returnedBalloonIndex, Rect *returnedRectangle)
  2293. {
  2294. #pragma unused (pWindow, pData, localMouse, returnedRectangle)
  2295.  
  2296.     *returnedBalloonIndex = iHelpTextContent;
  2297.     
  2298.     return noErr;
  2299.     
  2300. } // TextGetBalloon
  2301.  
  2302. // --------------------------------------------------------------------------------------------------------------
  2303.  
  2304. static long TextCalculateIdleTime(WindowRef pWindow, WindowDataPtr pData)
  2305. {
  2306. #pragma unused (pWindow, pData)
  2307.  
  2308.     if ( (gMachineInfo.amInBackground) || (! (**(((TextDataPtr) pData)->hTE)).active) )
  2309.         return(0x7FFFFFF);
  2310.     else
  2311.         return(1);
  2312.         
  2313. } // TextCalculateIdleTime
  2314.  
  2315. // --------------------------------------------------------------------------------------------------------------
  2316.  
  2317. static OSErr    TextAdjustCursor(WindowRef pWindow, WindowDataPtr pData, 
  2318.                         Point * localMouse, Rect * globalRect)
  2319. {
  2320. #pragma unused (pWindow, globalRect)
  2321.  
  2322.     OSErr            anErr = noErr;
  2323.     CursHandle        theCross;
  2324.     RgnHandle        hilightRgn;
  2325.     
  2326.     if (gMachineInfo.haveDragMgr)
  2327.         {
  2328.         hilightRgn = NewRgn();
  2329.         TEGetHiliteRgn(hilightRgn, ((TextDataPtr) pData)->hTE);
  2330.         if (PtInRgn(*localMouse, hilightRgn))
  2331.             {
  2332.             SetCursor(&qd.arrow);
  2333.             DisposeRgn(hilightRgn);
  2334.             return eActionAlreadyHandled;    
  2335.             }
  2336.     
  2337.         DisposeRgn(hilightRgn);
  2338.         }
  2339.         
  2340.     theCross = GetCursor(iBeamCursor);
  2341.     if (theCross)
  2342.         {
  2343.         char    oldState;
  2344.         
  2345.         oldState = HGetState((Handle) theCross);
  2346.         HLock((Handle) theCross);
  2347.         SetCursor(*theCross);
  2348.         HSetState((Handle) theCross, oldState);
  2349.         anErr = eActionAlreadyHandled;
  2350.         }
  2351.         
  2352.     return anErr;
  2353.     
  2354. } // TextAdjustCursor
  2355.  
  2356. // --------------------------------------------------------------------------------------------------------------
  2357.  
  2358. short gNilCaretProc[] = { 
  2359.                         0x584F,         // ADDQ.W    #$4, A7
  2360.                         0x4E75};        // RTS
  2361.  
  2362. // --------------------------------------------------------------------------------------------------------------
  2363.  
  2364. static OSErr    TextPrintPage(WindowRef pWindow, WindowDataPtr pData,
  2365.                     Rect * pageRect, long *pageNum)
  2366. {
  2367. #pragma unused (pWindow)
  2368.  
  2369.     OSErr        anErr = noErr;
  2370.     short        footerHeight;
  2371.     TEHandle    hTE;
  2372.     Rect        areaForThisPage;
  2373.     short        ourPage = 1;
  2374.     Boolean        documentHasFormControl = Count1Resources(kFormResource) != 0;
  2375.     
  2376.     // calculate area for the footer (page number)
  2377.     {
  2378.     FontInfo    theInfo;
  2379.     
  2380.     TextFont(0);
  2381.     TextSize(0);
  2382.     TextFace(normal);
  2383.     GetFontInfo(&theInfo);
  2384.     footerHeight = (theInfo.ascent + theInfo.descent + theInfo.leading) << 1;
  2385.     }
  2386.     
  2387.     // duplicate the text edit record, disable the selection before swapping the new port in
  2388.     hTE = ((TextDataPtr) pData)->hTE;
  2389.     TEDeactivate(hTE);
  2390.     
  2391.     anErr = HandToHand((Handle*) &hTE);
  2392.     nrequire(anErr, DuplicateTE);
  2393.  
  2394.     // turn off outline hilighting -- because the window is disabled while
  2395.     // printing is going on, but we don't want that disabled hilight to draw
  2396.     TEFeatureFlag(teFOutlineHilite, teBitClear, ((TextDataPtr) pData)->hTE);
  2397.         
  2398.     // now HERE'S a real hack!  Under certain conditions, Text Edit will draw the
  2399.     // cursor, even if you said the edit record is inactive!  This happens when
  2400.     // the internal state sez that the cursor hasn't been drawn yet.  Lucky
  2401.     // for us, the caret is drawn through a hook, which we replace with a NOP.
  2402.     (**hTE).caretHook = (CaretHookUPP) gNilCaretProc;
  2403.     
  2404.     // point the rectangles to be the page rect minus the footer
  2405.     areaForThisPage = *pageRect;
  2406.     areaForThisPage.bottom -= footerHeight;
  2407.     InsetRect(&areaForThisPage, kPrintMargins, kPrintMargins);
  2408.     (**hTE).viewRect = (**hTE).destRect = areaForThisPage;
  2409.  
  2410.     // recalculate the line breaks
  2411.     TECalText(hTE);
  2412.  
  2413.     // point it at the printing port.
  2414.     (**hTE).inPort = qd.thePort;
  2415.  
  2416.     // now loop over all pages doing page breaking until we find our current
  2417.     // page, which we print, and then return.
  2418.     {
  2419.     Rect    oldPageHeight = (**hTE).viewRect;
  2420.     short    currentLine = 0;
  2421.     long    prevPageHeight = 0;
  2422.  
  2423.     while (ourPage <= *pageNum)
  2424.         {
  2425.         long    currentPageHeight = 0;
  2426.                     
  2427.         // calculate the height including the current page, breaks
  2428.         // when one of three things happen:
  2429.         // 1) adding another line to this page would go beyond the length of the page
  2430.         // 2) a picture needs to be broken to the next page (NOT YET IMPLEMENTED)
  2431.         // 3) we run out of lines for the document 
  2432.         // 4) if the line has a page break (defined as a non breaking space w/o a PICT)
  2433.  
  2434.         // POTENTIAL BUG CASES:
  2435.         // If a single line > the page height.  Can that happen?  If so, we need to 
  2436.         // add something to handle it.
  2437.         do
  2438.             {
  2439.             long currentLineHeight;
  2440.             
  2441.             // zero based count -- but one based calls to TEGetHeight 
  2442.             currentLineHeight = TEGetHeight(currentLine+1, currentLine+1, hTE);
  2443.                 
  2444.             // if adding this line would just be too much, break out of here
  2445.             if ((currentLineHeight + currentPageHeight) > (areaForThisPage.bottom - areaForThisPage.top))
  2446.                 break;
  2447.                 
  2448.             ++ currentLine;
  2449.             currentPageHeight += currentLineHeight;
  2450.             
  2451.             // if this line had a page break on it, break out of pagination
  2452.             if (documentHasFormControl && LineHasPageBreak(currentLine-1, hTE))
  2453.                 break;
  2454.                 
  2455.             } while (currentLine < (**hTE).nLines);
  2456.         
  2457.         // if this the page we are trying to print
  2458.         if (ourPage == *pageNum)
  2459.             {
  2460.             Str255        pageString;
  2461.             RgnHandle    oldRgn = NewRgn();
  2462.             
  2463.             // move onto the next page via offset by the previous pages -- but
  2464.             // clip to the current page height because we wouldn't want to see
  2465.             // half of a line from the next page at the bottom of a page.
  2466.             OffsetRect(&oldPageHeight, 0, -(prevPageHeight));
  2467.             oldPageHeight.bottom = oldPageHeight.top + currentPageHeight;
  2468.             (**hTE).destRect = oldPageHeight;
  2469.             
  2470.             // clip to this area as well
  2471.             areaForThisPage.bottom = areaForThisPage.top + currentPageHeight;
  2472.             GetClip(oldRgn);
  2473.             ClipRect(&areaForThisPage);
  2474.             
  2475.             // draw the edit record, plus our cool pictures    
  2476.             TEUpdate(&areaForThisPage, hTE); 
  2477.             DrawPictures(pData, hTE);
  2478.             
  2479.             // restore the clip
  2480.             SetClip(oldRgn);
  2481.             DisposeRgn(oldRgn);
  2482.             
  2483.             // Draw the page string at the bottom of the page, centered
  2484.             pageString[0] = 2;
  2485.             pageString[1] = '-';
  2486.             NumToString(*pageNum, &pageString[2]);
  2487.             pageString[0] += pageString[2];
  2488.             pageString[2] = ' ';
  2489.             pageString[++pageString[0]] = ' ';
  2490.             pageString[++pageString[0]] = '-';
  2491.             
  2492.             MoveTo(
  2493.                 pageRect->left + 
  2494.                     ((pageRect->right - pageRect->left) >> 1) - 
  2495.                     (StringWidth(pageString)>>1),
  2496.                 pageRect->bottom - kPrintMargins);
  2497.                 
  2498.             DrawString(pageString);
  2499.             
  2500.             // if we have completed all pages
  2501.             if (currentLine >= (**hTE).nLines)
  2502.                 {
  2503.                 // tell it to stop printing
  2504.                 *pageNum = -1;
  2505.                 }
  2506.                 
  2507.             // get out of here!
  2508.             break;
  2509.             }
  2510.     
  2511.         // move onto the next page via count
  2512.         ++ourPage;
  2513.         
  2514.         // and the list of pages before now includes this page we just finished
  2515.         prevPageHeight += currentPageHeight;
  2516.         
  2517.         }
  2518.     
  2519.     }
  2520.     
  2521.     
  2522.     // restore text for visible page if done
  2523.     if (*pageNum == -1)
  2524.         {
  2525.         TEFeatureFlag(teFOutlineHilite, teBitSet, ((TextDataPtr) pData)->hTE);
  2526.         TECalText(((TextDataPtr) pData)->hTE);
  2527.         if (pData->originalFileType != 'ttro')
  2528.             TEActivate(((TextDataPtr) pData)->hTE);
  2529.         }
  2530.         
  2531. // FALL THROUGH EXCEPTION HANDLING
  2532.  
  2533.     // Dispose this way to avoid disposing of any owned objects
  2534.     DisposeHandle((Handle) hTE);
  2535. DuplicateTE:
  2536.  
  2537.     return anErr;
  2538.     
  2539. } // TextPrintPage
  2540.  
  2541. // --------------------------------------------------------------------------------------------------------------
  2542.  
  2543. static OSErr    TextMakeWindow(WindowRef pWindow, WindowDataPtr pData)
  2544. {
  2545.     #pragma unused(pWindow)
  2546.  
  2547.     OSErr                anErr = noErr;
  2548.  
  2549.     pData->bumpUntitledCount    = true;
  2550.     
  2551.     pData->pScrollContent         = (ScrollContentProc)    TextScrollContent;
  2552.     pData->pAdjustSize             = (AdjustSizeProc)        TextAdjustSize;
  2553.     pData->pGetDocumentRect     = (GetDocumentRectProc)    TextGetDocumentRect;
  2554.     pData->pAdjustMenus             = (AdjustMenusProc)        TextAdjustMenus;
  2555.     pData->pCommand                 = (CommandProc)            TextCommand;
  2556.  
  2557.     pData->pCloseWindow         = (CloseWindowProc)        TextCloseWindow;
  2558.     pData->pFilterEvent         = (FilterEventProc)        TextFilterEvent;
  2559.     pData->pActivateEvent         = (ActivateEventProc)    TextActivateEvent;
  2560.     pData->pUpdateWindow         = (UpdateWindowProc)    TextUpdateWindow;
  2561.     pData->pPrintPage             = (PrintPageProc)        TextPrintPage;
  2562.  
  2563.     // we only support keydowns and editing for modifable docs
  2564.     if (pData->originalFileType != 'ttro')
  2565.         {
  2566.         pData->pKeyEvent             = (KeyEventProc)            TextKeyEvent;
  2567.         pData->pContentClick        = (ContentClickProc)        TextContentClick;
  2568.         pData->pAdjustCursor        = (AdjustCursorProc)        TextAdjustCursor;
  2569.         pData->pGetBalloon            = (GetBalloonProc)            TextGetBalloon;
  2570.         pData->pCalculateIdleTime    = (CalculateIdleTimeProc)    TextCalculateIdleTime;
  2571.         
  2572.         // We can always reference our Drag handlers, because they will not be called if we
  2573.         // don't have the Drag Manager available. We needn't check here (it would be redundant).
  2574.         pData->pDragTracking        = (DragTrackingProc)    TextDragTracking;
  2575.         pData->pDragReceive            = (DragReceiveProc)        TextDragReceive;
  2576.  
  2577.         pData->documentAcceptsText    = true;
  2578.         }
  2579.         
  2580.     // leave room for the grow area at bottom
  2581.     pData->hasGrow                = true;
  2582.     pData->contentRect.bottom    -= kScrollBarSize;    
  2583.     if ((pData->contentRect.right - pData->contentRect.left) > kOnePageWidth)
  2584.         pData->contentRect.right = pData->contentRect.left + kOnePageWidth;
  2585.         
  2586.     ((TextDataPtr) pData)->hTE    = TEStyleNew(&pData->contentRect, &pData->contentRect);
  2587.     anErr = MemError();
  2588.     nrequire(anErr, TENewFailed);
  2589.         
  2590.     pData->hScrollAmount        = 0;
  2591.     pData->vScrollAmount        = TEGetHeight(0, 0, ((TextDataPtr) pData)->hTE);
  2592.  
  2593.     TEAutoView(true, ((TextDataPtr) pData)->hTE);
  2594.  
  2595.     // Setup our click loop to handle autoscrolling
  2596.     ((TextDataPtr) pData)->docClick = (**(((TextDataPtr) pData)->hTE)).clickLoop;
  2597.     TESetClickLoop(gMyClickLoop, ((TextDataPtr) pData)->hTE);
  2598.     
  2599.     // if we have a data fork, read the contents into the record    
  2600.     if (pData->dataRefNum != -1)
  2601.         {
  2602.         long    dataSize;
  2603.         
  2604.         GetEOF(pData->dataRefNum, &dataSize);
  2605.         if (dataSize > kMaxLength)
  2606.             anErr = eDocumentTooLarge;
  2607.         else
  2608.             {
  2609.             Handle    tempHandle = NewHandle(dataSize);
  2610.             anErr = MemError();
  2611.             if (anErr == noErr)
  2612.                 {
  2613.                 // read the text in
  2614.                 SetFPos(pData->dataRefNum, fsFromStart, 0);
  2615.                 anErr = FSRead(pData->dataRefNum, &dataSize, * tempHandle);                
  2616.  
  2617.                 // then insert it.
  2618.                 if (anErr == noErr)
  2619.                     {
  2620.                     HLock(tempHandle);
  2621.                     TEStyleInsert(*tempHandle, dataSize, nil, ((TextDataPtr) pData)->hTE);
  2622.                     anErr = MemError();
  2623.                     }
  2624.                 DisposeHandle(tempHandle);
  2625.                 }
  2626.             
  2627.             }
  2628.         
  2629.         }
  2630.     nrequire(anErr, ReadData);
  2631.     
  2632.     // if we have a resource fork, read the contents
  2633.     if (pData->resRefNum != -1)
  2634.         {
  2635.         short    oldResFile = CurResFile();
  2636.         Handle    theStyle;
  2637.         
  2638.         // read the style information
  2639.         UseResFile(pData->resRefNum);
  2640.         theStyle = Get1Resource('styl', 128);
  2641.         if (theStyle)
  2642.             {
  2643.             HNoPurge(theStyle);
  2644.             TEUseStyleScrap(0, 32767, (StScrpHandle) theStyle, true, ((TextDataPtr) pData)->hTE);
  2645.             ReleaseResource(theStyle);
  2646.             }
  2647.  
  2648.         // if we have sound, load it in and detach it
  2649.         {
  2650.         Handle    soundHandle = Get1Resource('snd ', kSoundBase);
  2651.         if (soundHandle)
  2652.             {
  2653.             HNoPurge(soundHandle);
  2654.             DetachResource(soundHandle);
  2655.             ((TextDataPtr) pData)->soundHandle = soundHandle;
  2656.             }
  2657.         }
  2658.  
  2659.  
  2660.         UseResFile(oldResFile);
  2661.         }
  2662.             
  2663.     // hook out drawing of the non-breaking space for read only documents,
  2664.     // for modifiable documents, enable outline hiliting (ie, when TE window
  2665.     // isn't in front, show the gray outline)
  2666.     if (pData->originalFileType == 'ttro')
  2667.         {
  2668.         UniversalProcPtr    hookRoutine = (UniversalProcPtr)gMyDrawGlue;
  2669.         
  2670.         TECustomHook(intDrawHook, &hookRoutine, ((TextDataPtr) pData)->hTE);
  2671.         }
  2672.     else
  2673.         {
  2674.         TEFeatureFlag(teFOutlineHilite, teBitSet, ((TextDataPtr) pData)->hTE);
  2675.         }
  2676.  
  2677.     // make a TSM document if this is editable
  2678.     if     (
  2679.         (pData->originalFileType != 'ttro') &&
  2680.         (gMachineInfo.haveTSMTE)
  2681.         )
  2682.         {
  2683.         OSType    supportedInterfaces[1];
  2684.  
  2685.         supportedInterfaces[0] = kTSMTEInterfaceType;
  2686.         
  2687.         if (NewTSMDocument(1, supportedInterfaces, 
  2688.             &pData->docTSMDoc, (long)&pData->docTSMRecHandle) == noErr)
  2689.             {
  2690.             long response;
  2691.  
  2692.             (**(pData->docTSMRecHandle)).textH                 = ((TextDataPtr) pData)->hTE;
  2693.             if ((Gestalt(gestaltTSMTEVersion, &response) == noErr) && (response == gestaltTSMTE1))
  2694.                 (**(pData->docTSMRecHandle)).preUpdateProc     = gTSMPreUpdateProc;
  2695.             (**(pData->docTSMRecHandle)).postUpdateProc     = gTSMPostUpdateProc;
  2696.             (**(pData->docTSMRecHandle)).updateFlag         = kTSMTEAutoScroll;
  2697.             (**(pData->docTSMRecHandle)).refCon             = (long)pData;
  2698.             }
  2699.         }
  2700.  
  2701.     // now we have added text, so adjust views and such as needed
  2702.     TESetSelect(0, 0, ((TextDataPtr) pData)->hTE);
  2703.     RecalcTE(pData, true);
  2704.     AdjustTE(pData, true);
  2705.  
  2706.     // ???? Hack to get around a 7.0 TextEdit bug.  If you are pasting a multiple
  2707.     // line clipboard into TE, *and* the TextEdit record is new, *and* the selection
  2708.     // is at the begining of the doc (0,0 as above), *and* you haven't moved the
  2709.     // cursor around at all, then TE pastes thinking it's at the end of the line,
  2710.     // when it really should be at the begining.  Then if you <cr> with the cursor
  2711.     // visible, it'll leave a copy behind.  
  2712.     
  2713.     // I'm not happy with this, but I don't know another way around the problem.
  2714.     if (pData->originalFileType != 'ttro') 
  2715.         {
  2716.         TEKey(0x1F, ((TextDataPtr) pData)->hTE);
  2717.         TEKey(0x1E, ((TextDataPtr) pData)->hTE);
  2718.         }
  2719.     
  2720.     // <39> if this is a new document, convert the "system size", "system font", and
  2721.     // "application font" into real font IDs and sizes.  This is so that
  2722.     // if someone saves this document and opens it with another script
  2723.     // system, they don't get all huffy that the font changed on them.
  2724.     // It also solves problems with cut and paste to applications too stupid
  2725.     // to know that "zero" means system size.
  2726.     if (pData->dataRefNum == -1)
  2727.         {
  2728.         TEHandle    hTE = ((TextDataPtr) pData)->hTE;
  2729.         short        mode = doAll;
  2730.         TextStyle    theStyle;
  2731.     
  2732.         TEContinuousStyle(&mode, &theStyle, hTE);
  2733.         if (theStyle.tsSize == 0)
  2734.             theStyle.tsSize = GetDefFontSize();
  2735.         if (theStyle.tsFont == systemFont)
  2736.             theStyle.tsFont = GetSysFont();
  2737.         if (theStyle.tsFont == applFont)
  2738.             theStyle.tsFont = GetAppFont();
  2739.             
  2740.         mode = doAll;
  2741.         TESetStyle(mode, &theStyle, false, hTE);
  2742.         }
  2743.  
  2744.     // if stationary, use untitled and close down the files
  2745.     if (pData->originalFileType == 'sEXT')
  2746.         {
  2747.         pData->originalFileType = 'TEXT';
  2748.         pData->openAsNew = true;
  2749.         if (pData->resRefNum != -1)
  2750.             CloseResFile(pData->resRefNum);
  2751.         if (pData->dataRefNum != -1)
  2752.             FSClose(pData->dataRefNum);
  2753.         pData->resRefNum = pData->dataRefNum = -1;
  2754.         }
  2755.         
  2756.     // initalize undo information
  2757.     ((TextDataPtr) pData)->prevCommandID = cNull;
  2758.     
  2759.     // if we have voices, add them to the menu
  2760.     if ( (gMachineInfo.haveTTS) && (!gAddedVoices) )
  2761.         {
  2762.         short    theVoiceCount;
  2763.         short    i, item;
  2764.         
  2765.         if (CountVoices( &theVoiceCount ) == noErr)
  2766.             {
  2767.             VoiceSpec            spec;                // A voice to add to the menu.
  2768.             VoiceDescription    description;        // Info about a voice.
  2769.             MenuHandle            voicesMenu = GetMenuHandle(mVoices);
  2770.  
  2771.             anErr = GetVoiceDescription( nil, &description, sizeof(description) );
  2772.             if (anErr == noErr)
  2773.                 {
  2774.                 gCurrentVoice = description.voice;
  2775.                 for (i = 1; i <= theVoiceCount; ++i)
  2776.                     {
  2777.                     if ( (GetIndVoice( i, &spec ) == noErr)  &&
  2778.                          (GetVoiceDescription( &spec, &description, sizeof(description) ) == noErr ) )
  2779.                         {
  2780.                         short    menuCount = CountMItems( voicesMenu );
  2781.                         
  2782.                         // first one we are adding == get rid of item already there
  2783.                         if ( (i == 1)  && (menuCount > 0) )
  2784.                             {
  2785.                             DeleteMenuItem( voicesMenu, 1 );
  2786.                             --menuCount;
  2787.                             }
  2788.                             
  2789.                         for ( item = 1; item <= menuCount; ++item )
  2790.                             {
  2791.                             Str255    itemText;
  2792.                             
  2793.                             GetMenuItemText( voicesMenu, item, itemText );
  2794.                             /*1st > 2nd*/
  2795.                             if ( IUCompString( itemText, description.name ) == 1 )
  2796.                                 break;                        // Found where name goes in list.
  2797.                             }
  2798.         
  2799.                         InsertMenuItem( voicesMenu, "\p ", item - 1 );
  2800.                         SetMenuItemText( voicesMenu, item, description.name );
  2801.                         
  2802.                         CheckItem(voicesMenu, item, 
  2803.                             ((gCurrentVoice.creator == spec.creator) && (gCurrentVoice.id == spec.id)) );
  2804.                         }
  2805.                     }
  2806.     
  2807.                 }
  2808.             
  2809.             gAddedVoices = true;
  2810.             }
  2811.             
  2812.         } // end of adding voices
  2813.         
  2814.     return noErr;
  2815.     
  2816. // EXCEPTION HANDLING
  2817. ReadData:
  2818.     TEDispose(((TextDataPtr) pData)->hTE);
  2819.     
  2820. TENewFailed:
  2821.  
  2822.     return anErr;
  2823.     
  2824. } // TextMakeWindow
  2825.  
  2826.  
  2827. // --------------------------------------------------------------------------------------------------------------
  2828.  
  2829. OSErr    TextPreflightWindow(PreflightPtr pPreflightData)
  2830. {    
  2831.     pPreflightData->continueWithOpen     = true;
  2832.     pPreflightData->wantVScroll            = true;
  2833.     pPreflightData->doZoom                = true;
  2834.     pPreflightData->makeProcPtr         = TextMakeWindow;
  2835.     if (pPreflightData->fileType != 'ttro')
  2836.         pPreflightData->openKind            = fsRdWrPerm;
  2837.     
  2838.     pPreflightData->storageSize         = sizeof(TextDataRecord);
  2839.  
  2840.     // get strings that mark the picture
  2841.     GetIndString(gPictMarker1, kTextStrings, iPictureMarker1);
  2842.     GetIndString(gPictMarker2, kTextStrings, iPictureMarker2);
  2843.     
  2844.     return noErr;
  2845.     
  2846. } // TextPreflightWindow
  2847.  
  2848. // --------------------------------------------------------------------------------------------------------------
  2849.  
  2850. void TextGetFileTypes(OSType * pFileTypes, OSType * pDocumentTypes, short * numTypes)
  2851. {
  2852.     pFileTypes[*numTypes]         = 'TEXT';
  2853.     pDocumentTypes[*numTypes]     = kTextWindow;
  2854.     (*numTypes)++;
  2855.         
  2856.     pFileTypes[*numTypes]         = 'ttro';
  2857.     pDocumentTypes[*numTypes]     = kTextWindow;
  2858.     (*numTypes)++;
  2859.         
  2860.     pFileTypes[*numTypes]         = 'sEXT';
  2861.     pDocumentTypes[*numTypes]     = kTextWindow;
  2862.     (*numTypes)++;
  2863.         
  2864. } // TextGetFileTypes
  2865.  
  2866. // --------------------------------------------------------------------------------------------------------------
  2867.  
  2868.  
  2869.  
  2870. // TextAddContentsMenu checks if there is a contents list and, if there
  2871. // is, creates a new menu handle for the contents list and fills it with 
  2872. // the appropriate visible items
  2873.  
  2874. void TextAddContentsMenu(WindowDataPtr pData)
  2875. {
  2876.     MenuHandle    contentsMenu;
  2877.     Str255        menuStr;
  2878.     short        totalItems;
  2879.     short        index;
  2880.     OSErr        err;
  2881.     
  2882.     contentsMenu = GetMenuHandle(mContents);
  2883.     require(contentsMenu == nil, ContentsMenuAlreadyInstalled);
  2884.     
  2885.     // Is there a contents list?  If so, get the menu name 
  2886.     // and the number of items in the list
  2887.     
  2888.     if (TextGetContentsListItem(pData, 0, menuStr, nil, &totalItems) == noErr)
  2889.         {
  2890.         
  2891.         // create the menu and fill it with all the items
  2892.         // listed in the string list resource
  2893.         
  2894.         contentsMenu = NewMenu(mContents, menuStr);
  2895.         require(contentsMenu != nil, CantCreateContentsMenu);
  2896.         
  2897.         for (index = 1; index < totalItems; index++)
  2898.             {
  2899.             err = TextGetContentsListItem(pData, index, menuStr, nil, nil);
  2900.             require(err == noErr, CantGetItem);
  2901.             
  2902.             AppendMenu(contentsMenu, menuStr);
  2903.             }
  2904.  
  2905.         // add the menu to the menu bar, and redraw the menu bar
  2906.         InsertMenu(contentsMenu, 0);
  2907.         DrawMenuBar();
  2908.         }
  2909.     else
  2910.         {
  2911.         // no contents, do nothing
  2912.         }
  2913.     
  2914.     return;
  2915.     
  2916. // error handling
  2917. CantGetItem:
  2918. CantCreateContentsMenu:
  2919.     
  2920.     if (contentsMenu)     DisposeMenu(contentsMenu);
  2921.  
  2922. ContentsMenuAlreadyInstalled:
  2923.  
  2924.     return;
  2925.         
  2926. } // TextAddContentsMenu
  2927.  
  2928.  
  2929.  
  2930.  
  2931. // TextRemoveContentsMenu removes the contents menu, if any,
  2932. // and redraws the menu bar
  2933.  
  2934. static void TextRemoveContentsMenu(WindowDataPtr pData)
  2935. {
  2936. #pragma unused (pData)
  2937.  
  2938.     MenuHandle    contentsMenu;
  2939.     
  2940.     contentsMenu = GetMenuHandle(mContents);
  2941.     if (contentsMenu)
  2942.         {
  2943.         DeleteMenu(mContents);
  2944.         DisposeMenu(contentsMenu);
  2945.         DrawMenuBar();
  2946.         }
  2947.  
  2948. } // TextRemoveContentsMenu
  2949.  
  2950.  
  2951.  
  2952. // TextGetContentsListItem is a general utility routine for examining the
  2953. // contents menu list, returning the menu and search strings, and returning
  2954. // the total number of entries in the contents list.
  2955. //
  2956. // Pass 0 as itemNum to retrieve the strings for the contents menu title.
  2957. //
  2958. // Pass nil for menuStr, searchStr, or totalItems if you don't want that
  2959. // info returned.
  2960. //
  2961. // Returns eDocumentHasNoContentsEntries if there is no contents string list
  2962. // resource for the specified window
  2963.  
  2964. static OSErr TextGetContentsListItem(WindowDataPtr pData, short itemNum, 
  2965.                               StringPtr menuStr, StringPtr searchStr, 
  2966.                               short *totalItems)
  2967. {
  2968.  
  2969.     OSErr    err;
  2970.     short    oldResFile;
  2971.     short    menuItemNum;
  2972.     short    searchItemNum;
  2973.     Handle    contentsStrListHandle;
  2974.     
  2975.     // if no original resource file, don't bother
  2976.     if (pData->resRefNum == -1)    
  2977.         {
  2978.         return eDocumentHasNoContentsEntries;
  2979.         }
  2980.         
  2981.     err = noErr;
  2982.     
  2983.     oldResFile = CurResFile();
  2984.     UseResFile(pData->resRefNum);
  2985.     
  2986.     // two entries per item
  2987.     //
  2988.     // first (itemNum zero) is content menu title
  2989.     // (second -- itemNum one, search string for menu title -- is unused)
  2990.     
  2991.     menuItemNum = itemNum * 2 + 1;
  2992.     searchItemNum = menuItemNum + 1;
  2993.     
  2994.     contentsStrListHandle = Get1Resource('STR#', kContentsListID);
  2995.     if (contentsStrListHandle)
  2996.         {
  2997.         if (totalItems)    *totalItems = (*(short *)*contentsStrListHandle) / 2;
  2998.  
  2999.         if (menuStr)    GetIndString(menuStr, kContentsListID, menuItemNum);
  3000.         if (searchStr)    
  3001.             {
  3002.             GetIndString(searchStr, kContentsListID, searchItemNum);
  3003.         
  3004.             if (searchStr[0] == 0)
  3005.                 {
  3006.                 // search string was empty, so use the
  3007.                 // menu string as the search string
  3008.                 
  3009.                 GetIndString(searchStr, kContentsListID, menuItemNum);
  3010.                 }
  3011.             }
  3012.         }
  3013.     else
  3014.         {
  3015.         err = eDocumentHasNoContentsEntries;
  3016.         if (totalItems)    *totalItems = 0;
  3017.         }
  3018.     
  3019.     UseResFile(oldResFile);
  3020.     
  3021.     return err;
  3022. } // TextGetContentsListItem
  3023.  
  3024.  
  3025. // TextAdjustContentsMenu enables the items in the contents menu
  3026. //
  3027. // This routine is essentially a placeholder in case the contents
  3028. // menu really were to be dynamically enabled.
  3029.  
  3030. static OSErr TextAdjustContentsMenu(WindowDataPtr pData)
  3031. {
  3032. #pragma unused (pData)
  3033.     
  3034.     EnableCommand(cSelectContents);
  3035.     return(noErr);
  3036.     
  3037. } // TextAdjustContentsMenu
  3038.  
  3039.